// ─── Screenshot orchestrator ──────────────────────────────────────────────────
// Try live capture → mask → annotate → upload to Vercel Blob.
// Falls back to synthesized card if live capture fails.

import { put } from "@vercel/blob";
import { captureLiveScreenshot } from "./capture-live";
import { maskVendorBranding } from "./mask";
import { annotateScreenshot } from "./annotator";
import { synthesizeScreenshot } from "./synthesize";
import type { EngineQueryResult } from "../agent";

const BLOB_PREFIX = "ai-search-verification";

export async function captureAndUploadScreenshot(
  result: EngineQueryResult,
  brandName: string,
): Promise<string | null> {
  if (!process.env.BLOB_READ_WRITE_TOKEN) return null;

  try {
    let imageBuffer: Buffer;

    const live = await captureLiveScreenshot(result.engineInternalName, result.query);

    if (live) {
      const masked = await maskVendorBranding(live, result.engineInternalName);
      imageBuffer = await annotateScreenshot(masked, brandName, result.brandMentioned);
    } else {
      const synth = synthesizeScreenshot(result);
      imageBuffer = await annotateScreenshot(synth, brandName, result.brandMentioned);
    }

    const filename = buildFilename(result);
    const { url } = await put(filename, imageBuffer, {
      access: "public",
      contentType: "image/png",
    });

    return url;
  } catch {
    return null;
  }
}

function buildFilename(result: EngineQueryResult): string {
  const slug = result.query
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .slice(0, 40);
  const ts = Date.now();
  return `${BLOB_PREFIX}/${result.engineInternalName}/${slug}-${ts}.png`;
}
