import { chromium } from "playwright";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const baseUrl = process.argv[2] || "http://127.0.0.1:3000";
const here = dirname(fileURLToPath(import.meta.url));
const outputDirectory = join(here, "outputs");
await mkdir(outputDirectory, { recursive: true });

const browser = await chromium.launch({
  channel: "chrome",
  headless: true,
  args: ["--enable-webgl", "--ignore-gpu-blocklist", "--use-angle=default"],
});
const context = await browser.newContext({
  viewport: { width: 1440, height: 900 },
  deviceScaleFactor: 1,
  colorScheme: "light",
});
const page = await context.newPage();
page.setDefaultTimeout(90_000);
const pageErrors = [];
const networkFailures = [];

page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) => {
  const url = new URL(request.url());
  networkFailures.push({
    host: url.host,
    path: url.pathname,
    resourceType: request.resourceType(),
    error: request.failure()?.errorText || "unknown",
  });
});

try {
  await page.goto(baseUrl, { waitUntil: "domcontentloaded", timeout: 60_000 });
  await page.waitForTimeout(2_000);
  await page.screenshot({
    path: join(outputDirectory, "orangeboard-landing-live.png"),
    animations: "disabled",
    timeout: 90_000,
  });
  const landingTitle = await page.title();

  await page.goto(`${baseUrl}/map?campaign=1`, { waitUntil: "domcontentloaded", timeout: 60_000 });
  await page.getByText("559 SF billboards", { exact: false }).waitFor({ timeout: 90_000 });
  await page.waitForTimeout(3_000);
  await page.screenshot({
    path: join(outputDirectory, "orangeboard-map-live.png"),
    animations: "disabled",
    timeout: 90_000,
  });

  const blockingNetworkFailures = networkFailures.filter((failure) =>
    !(failure.error === "net::ERR_ABORTED" && (failure.path === "/" || failure.path.includes("hot-update"))),
  );
  const capture = {
    schemaVersion: 1,
    capturedAt: new Date().toISOString(),
    baseUrl,
    landingTitle,
    mapBillboardLabel: await page.getByText("559 SF billboards", { exact: false }).first().textContent(),
    viewport: await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight, devicePixelRatio: window.devicePixelRatio })),
    userAgent: await page.evaluate(() => navigator.userAgent),
    pageErrors,
    networkFailures,
    blockingNetworkFailures,
  };
  await writeFile(join(outputDirectory, "orangeboard-live-capture.json"), `${JSON.stringify(capture, null, 2)}\n`, "utf8");
  console.log(JSON.stringify(capture, null, 2));

  if (pageErrors.length || blockingNetworkFailures.length) process.exitCode = 1;
} finally {
  await browser.close();
}
