/**
 * Visual Annotation — Overlay Renderer
 * ──────────────────────────────────────
 * Composites annotation specs onto a screenshot buffer using @napi-rs/canvas.
 *
 * Internal module — vendor names permitted in code; forbidden in user-facing output.
 */

import type { AnnotationSpec } from "./annotation-generator";

export async function renderAnnotatedScreenshot(
  buffer: Buffer,
  annotations: AnnotationSpec[],
): Promise<Buffer> {
  if (annotations.length === 0) return buffer;

  // Dynamic import to avoid initialization at module load
  const { createCanvas, loadImage } = await import("@napi-rs/canvas");

  const img = await loadImage(buffer);
  const canvas = createCanvas(img.width, img.height);
  const ctx = canvas.getContext("2d");

  // Draw original screenshot
  ctx.drawImage(img, 0, 0);

  for (const ann of annotations) {
    const { x, y, width, height } = ann.boundingBox;
    const cx = Math.max(0, x);
    const cy = Math.max(0, y);
    const cw = Math.min(width, img.width - cx);
    const ch = Math.min(height, img.height - cy);

    // Semi-transparent fill
    ctx.fillStyle = hexWithAlpha(ann.color, 0.12);
    ctx.fillRect(cx, cy, cw, ch);

    // Opaque border
    ctx.strokeStyle = ann.color;
    ctx.lineWidth = 2.5;
    ctx.strokeRect(cx + 1, cy + 1, cw - 2, ch - 2);

    // Number badge (circle in top-left corner of bbox)
    const badgeR = 12;
    const badgeX = cx + badgeR + 4;
    const badgeY = cy + badgeR + 4;
    ctx.beginPath();
    ctx.arc(badgeX, badgeY, badgeR, 0, Math.PI * 2);
    ctx.fillStyle = ann.color;
    ctx.fill();
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold 11px sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(String(ann.number), badgeX, badgeY);

    // Short label below/above badge
    const labelX = cx + badgeR * 2 + 10;
    const labelY = cy + badgeR + 4;
    const labelText = ann.shortLabel.slice(0, 28);
    const labelW = Math.min(labelText.length * 6.5 + 10, cw - badgeR * 2 - 20);
    const labelH = 16;
    ctx.fillStyle = ann.color;
    ctx.fillRect(labelX, labelY - 8, labelW, labelH);
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold 9px sans-serif";
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    ctx.fillText(labelText, labelX + 4, labelY);
  }

  return canvas.toBuffer("image/png") as unknown as Buffer;
}

function hexWithAlpha(hex: string, alpha: number): string {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return `rgba(${r},${g},${b},${alpha})`;
}
