// ─── Live screenshot capture ──────────────────────────────────────────────────
// Only supported for engines that have a navigable public URL (Perplexity, Gemini).

import { getBrowser } from "./browser-pool";

const CAPTURABLE_URLS: Partial<Record<string, (query: string) => string>> = {
  Perplexity: (q) => `https://www.perplexity.ai/search?q=${encodeURIComponent(q)}`,
  Gemini: (q) => `https://gemini.google.com/app?hl=en#q=${encodeURIComponent(q)}`,
};

const CAPTURE_TIMEOUT_MS = 20_000;
const WAIT_AFTER_LOAD_MS = 3_000;

export async function captureLiveScreenshot(
  engineInternalName: string,
  query: string,
): Promise<Buffer | null> {
  const urlFn = CAPTURABLE_URLS[engineInternalName];
  if (!urlFn) return null;

  try {
    const browser = await getBrowser();
    const page = await browser.newPage();

    try {
      await page.setViewport({ width: 1280, height: 800 });
      await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
          "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
      );

      await page.goto(urlFn(query), {
        waitUntil: "networkidle2",
        timeout: CAPTURE_TIMEOUT_MS,
      });

      await new Promise((r) => setTimeout(r, WAIT_AFTER_LOAD_MS));

      const screenshot = await page.screenshot({ type: "png", fullPage: false });
      return Buffer.from(screenshot);
    } finally {
      await page.close().catch(() => undefined);
    }
  } catch {
    return null;
  }
}
