import type { TextItem } from "pdfjs-dist/types/src/display/api";
import { LightBlock } from "./light-reader-types";
import { layoutPdfPages, PdfTextItem } from "./pdf-text-layout";
import { createLogger, DEBUG } from "../../utils/debug";

const log = createLogger("pdf");

type PdfJs = typeof import("pdfjs-dist/build/pdf.min.mjs");

const MAX_PDF_PAGES = 300;
// Journalise dans la console le texte brut renvoyé par pdf.js et les blocs obtenus (mise au point).
const DEBUG_PDF = true;

let pdfJsPromise: Promise<PdfJs> | undefined;
// Le PDF est re-demandé à chaque renvoi (mutations du DOM) : téléchargé et analysé une seule fois.
const cache = new Map<string, Promise<LightBlock[] | undefined>>();

/**
 * Charge pdf.js à la demande. Il tourne dans le thread principal (« fake worker »
 * via `globalThis.pdfjsWorker`) : un vrai Worker devrait venir du domaine Lisio,
 * ce qui est interdit en cross-origin sur les sites clients.
 */
function loadPdfJs(): Promise<PdfJs> {
  pdfJsPromise ??= Promise.all([
    import("pdfjs-dist/build/pdf.min.mjs"),
    import("pdfjs-dist/build/pdf.worker.min.mjs"),
  ]).then(([pdfjs, worker]) => {
    (globalThis as { pdfjsWorker?: unknown }).pdfjsWorker = worker;
    return pdfjs;
  });
  pdfJsPromise.catch(() => {
    pdfJsPromise = undefined;
  });
  return pdfJsPromise;
}

function isTextItem(item: object): item is TextItem {
  return "str" in item;
}

function logPdf(
  url: string,
  numPages: number,
  pages: PdfTextItem[][],
  blocks: LightBlock[],
) {
  if (!DEBUG) {
    return;
  }
  log.groupCollapsed(`${url} (${numPages} pages)`);
  for (const [index, items] of pages.entries()) {
    log.groupCollapsed(`page ${index + 1} : ${items.length} éléments`);
    log.table(
      items.map(({ str, x, y, height, hasEOL }) => ({
        str,
        x: Math.round(x * 10) / 10,
        y: Math.round(y * 10) / 10,
        height: Math.round(height * 10) / 10,
        hasEOL,
      })),
    );
    // Texte brut de la page, tel que renvoyé par pdf.js.
    log.log(
      items.map((item) => item.str + (item.hasEOL ? "\n" : "")).join(""),
    );
    log.groupEnd();
  }
  log.log("blocs", blocks);
  log.groupEnd();
}

async function readPdf(url: string): Promise<LightBlock[] | undefined> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  const data = new Uint8Array(await response.arrayBuffer());
  const pdfjs = await loadPdfJs();
  const loadingTask = pdfjs.getDocument({
    data,
    disableFontFace: true,
    useSystemFonts: false,
    disableAutoFetch: true,
    verbosity: pdfjs.VerbosityLevel.ERRORS,
  });
  try {
    const doc = await loadingTask.promise;
    const pages: PdfTextItem[][] = [];
    const pageCount = Math.min(doc.numPages, MAX_PDF_PAGES);
    for (let pageNumber = 1; pageNumber <= pageCount; pageNumber++) {
      const page = await doc.getPage(pageNumber);
      const content = await page.getTextContent();
      pages.push(
        content.items.filter(isTextItem).map((item) => ({
          str: item.str,
          x: Number(item.transform[4]),
          y: Number(item.transform[5]),
          width: item.width,
          height: item.height,
          hasEOL: item.hasEOL,
        })),
      );
      page.cleanup();
    }
    const blocks = layoutPdfPages(pages);
    if (DEBUG_PDF) {
      logPdf(url, doc.numPages, pages, blocks);
    }
    return blocks;
  } finally {
    await loadingTask.destroy();
  }
}

/**
 * Extrait le texte d'un PDF (titres et paragraphes, sans les images).
 * @param {string} url - URL absolue du PDF
 * @returns {Promise<LightBlock[] | undefined>} Les blocs, ou `undefined` si le PDF n'a pas pu être lu (CORS, PDF invalide…)
 */
function extractPdfBlocks(url: string): Promise<LightBlock[] | undefined> {
  let blocks = cache.get(url);
  if (blocks == undefined) {
    blocks = readPdf(url).catch((error: unknown) => {
      console.warn("[reading-mode] pdf extraction failed", url, error);
      return undefined;
    });
    cache.set(url, blocks);
  }
  return blocks;
}

function withAnchor(blocks: LightBlock[], a: number | undefined): LightBlock[] {
  return blocks.map((block) => ({ ...block, a }));
}

async function pdfBlocksOf(
  placeholder: Extract<LightBlock, { type: "pdf" }>,
): Promise<LightBlock[]> {
  // pdf.js n'est embarqué que dans l'extension : sur site, le PDF reste un simple lien.
  const blocks =
    __BUILD_TARGET__ === "extension"
      ? await extractPdfBlocks(placeholder.src)
      : undefined;
  if (blocks == undefined || blocks.length === 0) {
    // Illisible (scan, CORS…) : on garde au moins un lien vers le document.
    return withAnchor(
      [
        {
          type: "paragraph",
          c: [
            {
              t: "a",
              href: placeholder.src,
              blank: true,
              c: [placeholder.title],
            },
          ],
        },
      ],
      placeholder.a,
    );
  }
  // Tous les blocs défilent jusqu'à l'élément qui affiche le PDF sur la page hôte.
  return withAnchor(
    [{ type: "heading", level: 2, c: [placeholder.title] }, ...blocks],
    placeholder.a,
  );
}

/**
 * Remplace les PDF intégrés repérés par light-extract.ts par leur texte.
 * @param {LightBlock[]} blocks - Blocs extraits de la page hôte
 * @returns {Promise<LightBlock[]>} Les blocs, sans aucun bloc `pdf`
 */
async function resolvePdfPlaceholders(
  blocks: LightBlock[],
): Promise<LightBlock[]> {
  const resolved: LightBlock[] = [];
  for (const block of blocks) {
    if (block.type === "pdf") {
      resolved.push(...(await pdfBlocksOf(block)));
    } else if (block.type === "list") {
      for (const item of block.items) {
        item.children = await resolvePdfPlaceholders(item.children);
      }
      resolved.push(block);
    } else {
      resolved.push(block);
    }
  }
  return resolved;
}

export { extractPdfBlocks, resolvePdfPlaceholders };
