import fs from "fs/promises";
import path from "path";
import { createRequire } from "module";
const moduleRequire = createRequire(path.join(process.cwd(), "package.json"));
const pdfJsPackageRoot = path.dirname(moduleRequire.resolve("pdfjs-dist/package.json"));
const cMapUrl = `${path.join(pdfJsPackageRoot, "cmaps")}${path.sep}`;
const standardFontDataUrl = `${path.join(pdfJsPackageRoot, "standard_fonts")}${path.sep}`;
const MIN_RENDER_SCALE = 2;
const MAX_RENDER_SCALE = 4;
const MAX_RENDER_DIMENSION = 2200;
const MAX_RENDER_PIXELS = 8e6;
function normalizePdfText(rawText) {
  const normalized = rawText.replace(/\s+/g, " ").trim();
  return normalized.length > 0 ? normalized : null;
}
function extractPdfTextContent(items) {
  if (!Array.isArray(items) || items.length === 0) return null;
  const collected = items.map((item) => typeof item?.str === "string" ? item.str : "").filter((value) => value.length > 0).join(" ");
  return normalizePdfText(collected);
}
function resolvePdfRenderScale(page) {
  const baseViewport = page.getViewport({ scale: 1 });
  const baseLargestDimension = Math.max(baseViewport.width, baseViewport.height);
  let scale = Math.min(
    MAX_RENDER_SCALE,
    Math.max(MIN_RENDER_SCALE, MAX_RENDER_DIMENSION / Math.max(baseLargestDimension, 1))
  );
  let viewport = page.getViewport({ scale });
  const pixelCount = viewport.width * viewport.height;
  if (pixelCount > MAX_RENDER_PIXELS) {
    scale *= Math.sqrt(MAX_RENDER_PIXELS / pixelCount);
    viewport = page.getViewport({ scale });
  }
  return Math.max(1, scale);
}
async function renderPdfPageToImageBuffer(page, canvasFactory) {
  const viewport = page.getViewport({ scale: resolvePdfRenderScale(page) });
  const canvasAndContext = canvasFactory.create(viewport.width, viewport.height);
  try {
    const renderTask = page.render({
      canvasContext: canvasAndContext.context,
      viewport
    });
    await renderTask.promise;
    const imageBuffer = canvasAndContext.canvas.toBuffer("image/png");
    return Buffer.isBuffer(imageBuffer) ? imageBuffer : Buffer.from(imageBuffer);
  } finally {
    canvasFactory.destroy(canvasAndContext);
  }
}
async function preparePdfPagesForOcr(filePath) {
  const { getDocument } = await import("pdfjs-dist/legacy/build/pdf.mjs");
  const data = new Uint8Array(await fs.readFile(filePath));
  const loadingTask = getDocument({
    data,
    cMapUrl,
    cMapPacked: true,
    standardFontDataUrl
  });
  const pdfDocument = await loadingTask.promise;
  try {
    const pages = [];
    for (let pageNumber = 1; pageNumber <= pdfDocument.numPages; pageNumber += 1) {
      const page = await pdfDocument.getPage(pageNumber);
      try {
        const textContent = await page.getTextContent();
        const extractedText = extractPdfTextContent(textContent.items);
        if (extractedText) {
          pages.push({
            pageNumber,
            extractedText,
            imageBuffer: null
          });
          continue;
        }
        pages.push({
          pageNumber,
          extractedText: null,
          imageBuffer: await renderPdfPageToImageBuffer(page, pdfDocument.canvasFactory)
        });
      } finally {
        page.cleanup();
      }
    }
    return {
      pageCount: pdfDocument.numPages,
      pages
    };
  } finally {
    await loadingTask.destroy();
  }
}
export {
  preparePdfPagesForOcr
};
//# sourceMappingURL=pdfProcessing.js.map
