#!/usr/bin/env node

const target = process.argv[2] || process.env.SITE_URL;
const strategy = process.argv[3] || process.env.PAGESPEED_STRATEGY || "mobile";

if (!target) {
  console.error("Usage: npm run audit:pagespeed -- https://example.vercel.app [mobile|desktop]");
  process.exit(1);
}

const url = new URL("https://www.googleapis.com/pagespeedonline/v5/runPagespeed");
url.searchParams.set("url", target);
url.searchParams.set("strategy", strategy);
for (const category of ["performance", "accessibility", "best-practices", "seo"]) {
  url.searchParams.append("category", category);
}

const response = await fetch(url, {
  headers: {
    "User-Agent": "PopMediaPageSpeedAudit/1.0"
  }
});

if (!response.ok) {
  const body = await response.text();
  console.error(`PageSpeed request failed: ${response.status}`);
  console.error(body.slice(0, 1000));
  process.exit(1);
}

const data = await response.json();
const categories = data.lighthouseResult?.categories || {};
const scores = Object.fromEntries(
  Object.entries(categories).map(([key, value]) => [
    key,
    Math.round((value.score || 0) * 100)
  ])
);

console.log(`PageSpeed / Lighthouse for ${target}`);
console.log(`Strategy: ${strategy}`);
console.log(`Final URL: ${data.lighthouseResult?.finalDisplayedUrl || data.id || target}`);
console.log("");
for (const key of ["performance", "accessibility", "best-practices", "seo"]) {
  console.log(`${key}: ${scores[key] ?? "n/a"}/100`);
}

const audits = data.lighthouseResult?.audits || {};
const opportunities = [
  "largest-contentful-paint",
  "cumulative-layout-shift",
  "total-blocking-time",
  "meta-description",
  "document-title",
  "is-crawlable",
  "structured-data",
  "robots-txt"
]
  .map((key) => audits[key])
  .filter(Boolean)
  .map((audit) => ({
    title: audit.title,
    score: typeof audit.score === "number" ? Math.round(audit.score * 100) : "n/a",
    displayValue: audit.displayValue || ""
  }));

console.log("");
console.log("Key audits:");
for (const audit of opportunities) {
  console.log(`- ${audit.title}: ${audit.score}/100${audit.displayValue ? ` (${audit.displayValue})` : ""}`);
}

const seoScore = scores.seo ?? 0;
const accessibilityScore = scores.accessibility ?? 0;
const bestPracticesScore = scores["best-practices"] ?? 0;

if (seoScore < 90 || accessibilityScore < 80 || bestPracticesScore < 80) {
  process.exitCode = 1;
}
