import { LightBlock } from "./light-reader-types";

/**
 * Morceau de texte d'une page PDF (TextItem de pdf.js, simplifié).
 * Coordonnées PDF : `y` croît vers le haut de la page.
 */
interface PdfTextItem {
  hasEOL: boolean;
  /** Taille de police (hauteur en espace utilisateur). */
  height: number;
  str: string;
  width: number;
  x: number;
  y: number;
}

interface PdfLine {
  height: number;
  /** Bord droit du dernier morceau de la ligne. */
  right: number;
  text: string;
  x: number;
  y: number;
}

const MAX_BLOCKS = 5000;
/** Deux morceaux dont les `y` diffèrent de moins de `hauteur la plus petite × SAME_LINE_RATIO` sont sur la même ligne. */
const SAME_LINE_RATIO = 0.5;
/** Écart horizontal (× hauteur) au-delà duquel deux morceaux d'une ligne sont séparés par une espace. */
const WORD_GAP_RATIO = 0.1;
/** Écart vertical (× hauteur) au-delà duquel on change de paragraphe. */
const PARAGRAPH_GAP_RATIO = 1.6;
/** Variation de taille de police tolérée à l'intérieur d'un même bloc. */
const SIZE_TOLERANCE = 0.15;
const HEADING_RATIO = 1.3;
const HEADING_2_RATIO = 1.5;
const HEADING_1_RATIO = 1.8;
const HEADING_MAX_LENGTH = 120;
const HEADING_FORBIDDEN_END_RE = /[.,;:]$/u;
// Mot coupé en fin de ligne : « lec- » + « ture ».
const HYPHEN_END_RE = /\p{L}-$/u;
const LOWERCASE_START_RE = /^\p{Ll}/u;
// Puce en début de ligne : « • texte », « - texte »…
const BULLET_RE = /^[•▪◦●○■□‣⁃∙·*\-–—]\s+/u;
// Ligne terminée par une fin de phrase et nettement plus courte que le bloc : fin de paragraphe.
const SENTENCE_END_RE = /[.!?:]$/u;
const SHORT_LINE_RATIO = 0.85;
/** Deux blocs dont le haut diffère de moins de ce nombre de points sont considérés alignés (ordre gauche → droite). */
const SAME_TOP_TOLERANCE = 2;

function buildLines(items: PdfTextItem[]): PdfLine[] {
  const lines: PdfLine[] = [];
  let current: PdfLine | undefined;
  let lastEnd = 0;
  const close = () => {
    if (current != undefined) {
      current.text = current.text.replace(/\s+/gu, " ").trim();
      if (current.text !== "") {
        lines.push(current);
      }
    }
    current = undefined;
  };
  for (const item of items) {
    const hasText = item.str.trim() !== "";
    if (hasText) {
      const height = Math.abs(item.height);
      if (
        current != undefined &&
        Math.abs(item.y - current.y) >
          Math.min(current.height, height) * SAME_LINE_RATIO
      ) {
        close();
      }
      if (current == undefined) {
        current = { text: item.str, x: item.x, y: item.y, right: 0, height };
      } else {
        const needsSpace =
          !/\s$/u.test(current.text) &&
          !/^\s/u.test(item.str) &&
          item.x - lastEnd > Math.max(current.height, height) * WORD_GAP_RATIO;
        current.text += needsSpace ? ` ${item.str}` : item.str;
        current.height = Math.max(current.height, height);
      }
      lastEnd = item.x + item.width;
      current.right = lastEnd;
    } else if (current != undefined && item.str !== "" && !item.hasEOL) {
      current.text += " ";
    }
    if (item.hasEOL) {
      close();
    }
  }
  close();
  return lines;
}

/** Taille de police du texte courant : médiane des hauteurs de ligne, pondérée par le nombre de caractères. */
function bodySizeOf(lines: PdfLine[]): number {
  const sorted = [...lines].sort((a, b) => a.height - b.height);
  const total = sorted.reduce((sum, line) => sum + line.text.length, 0);
  let seen = 0;
  for (const line of sorted) {
    seen += line.text.length;
    if (seen * 2 >= total) {
      return line.height;
    }
  }
  return 0;
}

function headingLevelOf(line: PdfLine, bodySize: number): 1 | 2 | 3 | undefined {
  if (
    bodySize <= 0 ||
    line.text.length > HEADING_MAX_LENGTH ||
    HEADING_FORBIDDEN_END_RE.test(line.text)
  ) {
    return undefined;
  }
  const ratio = line.height / bodySize;
  if (ratio >= HEADING_1_RATIO) {
    return 1;
  }
  if (ratio >= HEADING_2_RATIO) {
    return 2;
  }
  return ratio >= HEADING_RATIO ? 3 : undefined;
}

function joinLines(text: string, next: string): string {
  if (HYPHEN_END_RE.test(text) && LOWERCASE_START_RE.test(next)) {
    return `${text.slice(0, -1)}${next}`;
  }
  return `${text} ${next}`;
}

type BlockKind = 1 | 2 | 3 | "item" | undefined;

interface PendingBlock {
  height: number;
  /** Titre (niveau), élément de liste (`item`) ou paragraphe (`undefined`). */
  kind: BlockKind;
  lastRight: number;
  lastY: number;
  maxRight: number;
  text: string;
  topY: number;
  x: number;
}

function kindOf(line: PdfLine, bodySize: number): BlockKind {
  if (BULLET_RE.test(line.text)) {
    return "item";
  }
  return headingLevelOf(line, bodySize);
}

function continues(pending: PendingBlock, line: PdfLine, kind: BlockKind): boolean {
  // Positif quand la ligne est sous la précédente ; négatif au changement de colonne.
  const gap = pending.lastY - line.y;
  const closeEnough =
    Math.abs(line.height - pending.height) <= pending.height * SIZE_TOLERANCE &&
    gap > 0 &&
    gap <= Math.max(line.height, pending.height) * PARAGRAPH_GAP_RATIO;
  if (!closeEnough) {
    return false;
  }
  if (
    pending.kind == undefined &&
    SENTENCE_END_RE.test(pending.text) &&
    pending.lastRight - pending.x <
      (pending.maxRight - pending.x) * SHORT_LINE_RATIO
  ) {
    return false;
  }
  if (pending.kind === "item") {
    // Suite d'un élément de liste : ligne sans puce, en retrait par rapport à la puce.
    return kind === undefined && line.x > pending.x + 1;
  }
  return kind === pending.kind;
}

/** Blocs d'une page, dans l'ordre du flux PDF (le texte d'une colonne reste groupé). */
function groupLines(lines: PdfLine[], bodySize: number): PendingBlock[] {
  const blocks: PendingBlock[] = [];
  let pending: PendingBlock | undefined;
  for (const line of lines) {
    const kind = kindOf(line, bodySize);
    if (pending != undefined && continues(pending, line, kind)) {
      pending.text = joinLines(pending.text, line.text);
      pending.lastY = line.y;
      pending.lastRight = line.right;
      pending.maxRight = Math.max(pending.maxRight, line.right);
      continue;
    }
    pending = {
      text: kind === "item" ? line.text.replace(BULLET_RE, "") : line.text,
      height: line.height,
      lastY: line.y,
      lastRight: line.right,
      maxRight: line.right,
      topY: line.y,
      x: line.x,
      kind,
    };
    blocks.push(pending);
  }
  return blocks;
}

/**
 * Remet les blocs dans l'ordre de lecture, de haut en bas puis de gauche à droite :
 * l'ordre du flux PDF est souvent celui de construction du document (pied de page en premier…).
 */
function sortBlocks(blocks: PendingBlock[]): PendingBlock[] {
  return [...blocks].sort((a, b) =>
    Math.abs(a.topY - b.topY) <= SAME_TOP_TOLERANCE ? a.x - b.x : b.topY - a.topY,
  );
}

function toBlocks(pendings: PendingBlock[]): LightBlock[] {
  const blocks: LightBlock[] = [];
  for (const pending of pendings) {
    if (pending.kind === "item") {
      const last = blocks[blocks.length - 1];
      const item = { c: [pending.text], children: [] };
      if (last?.type === "list") {
        last.items.push(item);
      } else {
        blocks.push({ type: "list", ordered: false, items: [item] });
      }
    } else if (pending.kind == undefined) {
      blocks.push({ type: "paragraph", c: [pending.text] });
    } else {
      blocks.push({ type: "heading", level: pending.kind, c: [pending.text] });
    }
  }
  return blocks;
}

function layoutPage(lines: PdfLine[], bodySize: number): LightBlock[] {
  return toBlocks(sortBlocks(groupLines(lines, bodySize)));
}

/**
 * Reconstruit titres et paragraphes à partir du texte brut des pages d'un PDF.
 * Les titres sont repérés par leur taille de police, nettement plus grande que
 * celle du texte courant, les listes par leurs puces. Les blocs de chaque page
 * sont remis dans l'ordre de lecture (haut → bas, gauche → droite).
 * Un repère « Page N » précède chaque page après la première.
 * @param {PdfTextItem[][]} pages - Les morceaux de texte de chaque page, dans l'ordre du PDF
 * @returns {LightBlock[]} Les blocs du mode lecture allégé
 */
function layoutPdfPages(pages: PdfTextItem[][]): LightBlock[] {
  const linesByPage = pages.map((items) => buildLines(items));
  const bodySize = bodySizeOf(linesByPage.flat());
  const blocks: LightBlock[] = [];
  for (const [index, lines] of linesByPage.entries()) {
    const pageBlocks = layoutPage(lines, bodySize);
    if (pageBlocks.length === 0) {
      continue;
    }
    if (index > 0 && blocks.length > 0) {
      blocks.push({ type: "paragraph", c: [`Page ${index + 1}`] });
    }
    blocks.push(...pageBlocks);
    if (blocks.length >= MAX_BLOCKS) {
      return blocks.slice(0, MAX_BLOCKS);
    }
  }
  return blocks;
}

export { layoutPdfPages };
export type { PdfTextItem };
