import fs from "fs/promises";
import { thumbPathFor } from "./store";

// Optional native deps — loaded lazily so the rest of the app keeps working
// if they're missing on a given host. We declare them as any to avoid hard
// type-resolution at build time before `npm install` has run.
type AnyMod = any; // eslint-disable-line @typescript-eslint/no-explicit-any

async function loadPdfjs(): Promise<AnyMod> {
  return (await import(/* webpackIgnore: true */ "pdfjs-dist/legacy/build/pdf.mjs" as string)) as AnyMod;
}
async function loadCanvas(): Promise<AnyMod> {
  return (await import(/* webpackIgnore: true */ "@napi-rs/canvas" as string)) as AnyMod;
}

// Best-effort PDF first-page thumbnail (WebP, ~320px wide).
// Returns true if the thumbnail was generated. Never throws — failures are
// logged and treated as "no thumbnail available".
export async function generatePdfThumbnail(pdfBuffer: Buffer, id: string): Promise<boolean> {
  try {
    const pdfjs     = await loadPdfjs();
    const canvasMod = await loadCanvas();

    const loadingTask = pdfjs.getDocument({
      data:            new Uint8Array(pdfBuffer),
      isEvalSupported: false,
      disableFontFace: true,
      useSystemFonts:  false,
      verbosity:       0,
    });
    const doc  = await loadingTask.promise;
    const page = await doc.getPage(1);

    const targetWidth = 320;
    const viewport1 = page.getViewport({ scale: 1 });
    const scale     = targetWidth / viewport1.width;
    const viewport  = page.getViewport({ scale });

    const canvas  = canvasMod.createCanvas(viewport.width, viewport.height);
    const ctx     = canvas.getContext("2d");
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, viewport.width, viewport.height);

    await page.render({ canvasContext: ctx, viewport }).promise;

    const webp = await canvas.encode("webp", 80);
    await fs.writeFile(thumbPathFor(id), webp);
    await doc.cleanup();
    await doc.destroy();
    return true;
  } catch (err) {
    console.warn("[thumbnail] PDF generation failed for", id, err instanceof Error ? err.message : err);
    return false;
  }
}

export async function generateImageThumbnail(imageBuffer: Buffer, id: string): Promise<boolean> {
  try {
    const canvasMod   = await loadCanvas();
    const img         = await canvasMod.loadImage(imageBuffer);
    const targetWidth = 320;
    const scale       = Math.min(1, targetWidth / img.width);
    const w = Math.round(img.width  * scale);
    const h = Math.round(img.height * scale);
    const canvas = canvasMod.createCanvas(w, h);
    const ctx    = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, w, h);
    const webp = await canvas.encode("webp", 80);
    await fs.writeFile(thumbPathFor(id), webp);
    return true;
  } catch (err) {
    console.warn("[thumbnail] image generation failed for", id, err instanceof Error ? err.message : err);
    return false;
  }
}
