// ─── Synthesized fallback screenshot ─────────────────────────────────────────
// Generates a meSEO-branded card image when live capture is unavailable.

import { createCanvas } from "@napi-rs/canvas";
import type { EngineQueryResult } from "../agent";

const WIDTH = 1280;
const HEIGHT = 800;
const BRAND_COLOR = "#4F46E5";       // meSEO indigo
const BG_COLOR = "#0F172A";          // dark navy
const TEXT_COLOR = "#F8FAFC";
const MUTED_COLOR = "#94A3B8";
const CARD_BG = "#1E293B";

export function synthesizeScreenshot(result: EngineQueryResult): Buffer {
  const canvas = createCanvas(WIDTH, HEIGHT);
  const ctx = canvas.getContext("2d");

  // Background
  ctx.fillStyle = BG_COLOR;
  ctx.fillRect(0, 0, WIDTH, HEIGHT);

  // Header bar
  ctx.fillStyle = BRAND_COLOR;
  ctx.fillRect(0, 0, WIDTH, 56);

  // meSEO label in header
  ctx.fillStyle = TEXT_COLOR;
  ctx.font = "bold 22px sans-serif";
  ctx.fillText("meSEO AI Search Verification", 24, 36);

  // Engine name + subtitle chip
  ctx.fillStyle = CARD_BG;
  roundRect(ctx, 24, 80, 500, 72, 8);
  ctx.fill();

  ctx.fillStyle = BRAND_COLOR;
  ctx.font = "bold 20px sans-serif";
  ctx.fillText(result.engineDisplayName, 40, 112);
  ctx.fillStyle = MUTED_COLOR;
  ctx.font = "14px sans-serif";
  ctx.fillText(result.engineSubtitle, 40, 134);

  // Query label
  ctx.fillStyle = MUTED_COLOR;
  ctx.font = "13px sans-serif";
  ctx.fillText("Query:", 24, 182);
  ctx.fillStyle = TEXT_COLOR;
  ctx.font = "16px sans-serif";
  ctx.fillText(truncate(result.query, 90), 24, 202);

  // Response preview card
  ctx.fillStyle = CARD_BG;
  roundRect(ctx, 24, 224, WIDTH - 48, 340, 8);
  ctx.fill();

  ctx.fillStyle = MUTED_COLOR;
  ctx.font = "12px sans-serif";
  ctx.fillText("AI Response Preview", 40, 248);

  const previewText = result.responseText ?? "No response captured.";
  ctx.fillStyle = TEXT_COLOR;
  ctx.font = "15px sans-serif";
  wrapText(ctx, previewText, 40, 272, WIDTH - 96, 22, 12);

  // Status row
  const statusY = 588;
  ctx.fillStyle = result.success ? "#22C55E" : "#EF4444";
  ctx.font = "bold 14px sans-serif";
  ctx.fillText(result.success ? "✓ Response captured" : "✗ Engine unavailable", 24, statusY);

  if (result.citationsCount > 0) {
    ctx.fillStyle = MUTED_COLOR;
    ctx.font = "14px sans-serif";
    ctx.fillText(`${result.citationsCount} citations`, 240, statusY);
  }

  // Footer watermark
  ctx.fillStyle = MUTED_COLOR;
  ctx.font = "12px sans-serif";
  ctx.fillText("Generated by meSEO — AI Search Verification", 24, HEIGHT - 20);

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

// ─── Canvas helpers ────────────────────────────────────────────────────────────

function roundRect(
  ctx: ReturnType<ReturnType<typeof createCanvas>["getContext"]>,
  x: number, y: number, w: number, h: number, r: number,
) {
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.quadraticCurveTo(x + w, y, x + w, y + r);
  ctx.lineTo(x + w, y + h - r);
  ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
  ctx.lineTo(x + r, y + h);
  ctx.quadraticCurveTo(x, y + h, x, y + h - r);
  ctx.lineTo(x, y + r);
  ctx.quadraticCurveTo(x, y, x + r, y);
  ctx.closePath();
}

function truncate(text: string, max: number): string {
  return text.length > max ? text.slice(0, max - 1) + "…" : text;
}

function wrapText(
  ctx: ReturnType<ReturnType<typeof createCanvas>["getContext"]>,
  text: string,
  x: number, y: number,
  maxWidth: number,
  lineHeight: number,
  maxLines: number,
) {
  const words = text.split(" ");
  let line = "";
  let lineCount = 0;

  for (const word of words) {
    const test = line ? `${line} ${word}` : word;
    const metrics = ctx.measureText(test);
    if (metrics.width > maxWidth && line) {
      ctx.fillText(line, x, y + lineCount * lineHeight);
      line = word;
      lineCount++;
      if (lineCount >= maxLines) {
        ctx.fillText(truncate(line, 60) + "…", x, y + lineCount * lineHeight);
        return;
      }
    } else {
      line = test;
    }
  }
  if (line) ctx.fillText(line, x, y + lineCount * lineHeight);
}
