import { DocumentReadError } from "../ingest/acceptedTypes";

/**
 * Decodes a HEIC/HEIF buffer to JPEG so the rest of the pipeline (sharp →
 * vision) never has to speak HEVC.
 *
 * Order:
 * 1. sharp — only works if this libvips build actually includes libheif/HEVC
 *    (the official prebuilds do not).
 * 2. `heic-convert` (libheif-js WASM) — portable fallback for iPhone photos.
 *
 * Throws {@link DocumentReadError} when neither decoder can read the file.
 */
export async function decodeHeicToJpeg(inputBuffer: Buffer): Promise<Buffer> {
  if (await canSharpDecodeHeic(inputBuffer)) {
    return inputBuffer;
  }

  try {
    const mod = await import("heic-convert");
    const convert = mod.default ?? (mod as unknown as typeof mod.default);
    const output = await convert({
      buffer: inputBuffer,
      format: "JPEG",
      quality: 0.9,
    });
    return Buffer.isBuffer(output) ? output : Buffer.from(output);
  } catch (error) {
    if (error instanceof DocumentReadError) throw error;
    console.warn("[ImageProcessor] HEIC-Konvertierung fehlgeschlagen:", error);
    throw new DocumentReadError(HEIC_DECODE_ERROR_MESSAGE, { cause: error });
  }
}

export const HEIC_DECODE_ERROR_MESSAGE =
  "Die HEIC/HEIF-Datei konnte nicht gelesen werden. Bitte exportiere den Beleg als JPEG, PNG oder PDF.";

async function canSharpDecodeHeic(buffer: Buffer): Promise<boolean> {
  try {
    const sharp = (await import("sharp")).default;
    const meta = await sharp(buffer).metadata();
    return Boolean(meta.width && meta.height);
  } catch {
    return false;
  }
}
