import type { Detection } from "./report-types";

const COLORS: Record<string, string> = {
  mold: "#dc2626",
  moisture: "#eab308",
  leak: "#2563eb",
};

export const LEGEND = [
  { color: COLORS.mold, label: "Red outline — suspected mold" },
  { color: COLORS.moisture, label: "Yellow outline — possible moisture" },
  { color: COLORS.leak, label: "Blue outline — possible water leakage" },
];

function loadImage(src: string) {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error("Could not read image"));
    img.src = src;
  });
}

/** Draw coloured outlines for each detection over the image and return a JPEG data URL. */
export async function annotateImage(dataUrl: string, detections: Detection[], maxWidth = 1280): Promise<string> {
  try {
    const img = await loadImage(dataUrl);
    const scale = Math.min(1, maxWidth / (img.naturalWidth || maxWidth));
    const canvas = document.createElement("canvas");
    canvas.width = Math.max(1, Math.round((img.naturalWidth || maxWidth) * scale));
    canvas.height = Math.max(1, Math.round((img.naturalHeight || maxWidth) * scale));
    const ctx = canvas.getContext("2d");
    if (!ctx) return dataUrl;
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    const line = Math.max(2, Math.round(canvas.width / 220));
    ctx.lineWidth = line;
    ctx.font = `${Math.max(12, Math.round(canvas.width / 45))}px sans-serif`;
    ctx.textBaseline = "top";

    detections.forEach((d, i) => {
      const box = d.box;
      if (!box) return;
      const color = COLORS[d.kind ?? "mold"] ?? COLORS.mold;
      const x = Math.max(0, box.x) * canvas.width;
      const y = Math.max(0, box.y) * canvas.height;
      const w = Math.min(1, box.w) * canvas.width;
      const h = Math.min(1, box.h) * canvas.height;
      ctx.strokeStyle = color;
      ctx.strokeRect(x, y, w, h);
      const label = `${i + 1}`;
      const pad = line * 2;
      const metrics = ctx.measureText(label);
      ctx.fillStyle = color;
      ctx.fillRect(x, Math.max(0, y - (line + 20)), metrics.width + pad * 2, line + 20);
      ctx.fillStyle = "#ffffff";
      ctx.fillText(label, x + pad, Math.max(0, y - (line + 18)));
    });

    return canvas.toDataURL("image/jpeg", 0.85);
  } catch {
    return dataUrl;
  }
}

export async function annotateAll(images: string[], detections: Detection[]) {
  return Promise.all(
    images.map((src, index) =>
      annotateImage(
        src,
        detections.filter((d) => (d.imageIndex ?? 0) === index),
      ),
    ),
  );
}