/**
 * Visual Annotation — Screenshot Capture
 * ─────────────────────────────────────────
 * Captures brand and competitor pages using the existing headless browser pool.
 * Returns raw PNG buffer + serialized DOM for element detection.
 *
 * Internal module — vendor names permitted in code; forbidden in user-facing output.
 */

import { getBrowser } from "../ai-search-verification/screenshots/browser-pool";

export interface CaptureResult {
  buffer: Buffer;
  dom: string;
}

export async function captureUrl(
  url: string,
  options: { viewport: "desktop" | "mobile"; fullPage: boolean },
): Promise<CaptureResult | null> {
  const viewportConfig =
    options.viewport === "mobile"
      ? { width: 390, height: 844 }
      : { width: 1280, height: 720 };

  let page: import("puppeteer-core").Page | null = null;

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

    await page.goto(url, {
      waitUntil: "networkidle2",
      timeout: 30_000,
    });

    const buffer = Buffer.from(
      await page.screenshot({
        type: "png",
        fullPage: options.fullPage,
        encoding: "binary",
      }) as Buffer,
    );

    const dom = await page.content();

    return { buffer, dom };
  } catch {
    return null;
  } finally {
    if (page) await page.close().catch(() => undefined);
  }
}
