import { callPageSpeedInsights } from "../../page-speed/psi-api";
import { extractCoreWebVitals } from "../../page-speed/core-web-vitals";
import { extractRenderBlockingResources } from "../../page-speed/render-blocking-resources";
import { extractImageOptimizationOpportunities } from "../../page-speed/image-optimization";
import { scorePageSpeed } from "../../page-speed/speed-scorer";
import type { PageSpeedInsights, PerPageSpeedAnalysis } from "../../page-speed/types";
import type { LiveVisualAnnotations } from "../types";

const MAX_PAGES = 3;
const SECTION_TIMEOUT_MS = 120_000;

function classifyPageLabel(url: string): string {
  const path = url.replace(/^https?:\/\/[^/]+/, "").toLowerCase();
  if (path === "/" || path === "") return "Homepage";
  if (/\/contact/i.test(path)) return "Contact Page";
  if (/\/(services?|treatments?|solutions?)/i.test(path)) return "Services Page";
  if (/\/about/i.test(path)) return "About Page";
  if (/\/(blog|news)/i.test(path)) return "Blog Page";
  if (/\/(products?|shop)/i.test(path)) return "Product Page";
  return "Page";
}

async function analyzePageSpeed(url: string): Promise<PerPageSpeedAnalysis> {
  const psiResponse = await callPageSpeedInsights(url, "mobile");
  const lh = psiResponse.lighthouseResult;
  const overallScore = Math.round((lh.categories.performance?.score ?? 0) * 100);

  const coreWebVitals = extractCoreWebVitals(psiResponse);
  const renderBlockingResources = extractRenderBlockingResources(psiResponse);
  const imageOpportunities = extractImageOptimizationOpportunities(psiResponse);

  // Top opportunities from PSI audits
  const opportunityAuditIds = [
    "unused-javascript",
    "unused-css-rules",
    "uses-text-compression",
    "uses-long-cache-ttl",
    "bootup-time",
  ];
  const topOpportunities = opportunityAuditIds
    .map((id) => lh.audits[id])
    .filter((a) => a && a.score !== null && a.score < 0.9)
    .map((a) => ({
      title: a!.title,
      description: a!.displayValue ?? "",
      wastedMs: a!.details?.overallSavingsMs,
      wastedBytes: a!.details?.overallSavingsBytes,
    }))
    .slice(0, 5);

  return {
    pageUrl: url,
    pageLabel: classifyPageLabel(url),
    strategy: "mobile",
    overallScore,
    coreWebVitals,
    renderBlockingResources,
    imageOpportunities,
    topOpportunities,
    dataFreshness: new Date().toISOString(),
  };
}

export async function aggregatePageSpeedInsights({
  brandDomain,
  vertical,
  liveVisualAnnotations,
}: {
  brandDomain: string;
  vertical: string;
  liveVisualAnnotations: LiveVisualAnnotations | null | undefined;
}): Promise<PageSpeedInsights | null> {
  const start = Date.now();

  // Use the same pages as Phase 12 (up to MAX_PAGES), falling back to homepage
  const pageUrls: string[] =
    liveVisualAnnotations?.perPageAnnotations.length
      ? liveVisualAnnotations.perPageAnnotations.slice(0, MAX_PAGES).map((p) => p.pageUrl)
      : [brandDomain];

  const pagePromises = pageUrls.map((url) => analyzePageSpeed(url));

  const timeoutPromise = new Promise<null>((resolve) =>
    setTimeout(() => resolve(null), SECTION_TIMEOUT_MS),
  );

  const settled = await Promise.race([
    Promise.allSettled(pagePromises),
    timeoutPromise,
  ]);

  if (settled === null) {
    console.warn("[page-speed-deep-dive] Section timeout reached");
    return null;
  }

  const perPageAnalyses: PerPageSpeedAnalysis[] = settled
    .filter(
      (r): r is PromiseFulfilledResult<PerPageSpeedAnalysis> => r.status === "fulfilled",
    )
    .map((r) => r.value);

  if (perPageAnalyses.length === 0) return null;

  return scorePageSpeed(perPageAnalyses, vertical, start);
}
