export async function loadBrowserPdf(sourceUrl: string) {
  const pdfjs = await import("pdfjs-dist");
  pdfjs.GlobalWorkerOptions.workerSrc = new URL(
    "pdfjs-dist/build/pdf.worker.min.mjs",
    import.meta.url,
  ).toString();
  const loadingTask = pdfjs.getDocument({ url: sourceUrl });
  const document = await loadingTask.promise;
  return { document, destroy: () => loadingTask.destroy() };
}

export async function renderPdfPageForOcr(
  document: Awaited<ReturnType<typeof loadBrowserPdf>>["document"],
  pageNumber: number,
  scale = 2,
): Promise<HTMLCanvasElement> {
  const page = await document.getPage(pageNumber);
  const viewport = page.getViewport({ scale });
  const canvas = window.document.createElement("canvas");
  canvas.width = Math.ceil(viewport.width);
  canvas.height = Math.ceil(viewport.height);
  const canvasContext = canvas.getContext("2d", { willReadFrequently: true });
  if (!canvasContext) throw new Error("浏览器无法创建 OCR 画布。");
  await page.render({ canvas, canvasContext, viewport }).promise;
  page.cleanup();
  return canvas;
}
