import type { PsiResponse } from "./psi-api";
import type { ImageOptimizationOpportunity } from "./types";

const IMAGE_AUDIT_IDS = [
  "uses-optimized-images",
  "uses-webp-images",
  "uses-responsive-images",
  "offscreen-images",
  "efficiently-encode-images",
] as const;

const MAX_OPPORTUNITIES = 5;

export function extractImageOptimizationOpportunities(
  psiResponse: PsiResponse,
): ImageOptimizationOpportunity[] {
  const audits = psiResponse.lighthouseResult.audits;
  const opportunities: ImageOptimizationOpportunity[] = [];

  for (const auditId of IMAGE_AUDIT_IDS) {
    if (opportunities.length >= MAX_OPPORTUNITIES) break;
    const audit = audits[auditId];
    if (!audit || audit.score === 1 || !audit.details?.items?.length) continue;

    const items = audit.details.items;
    for (const item of items) {
      if (opportunities.length >= MAX_OPPORTUNITIES) break;

      const url =
        typeof item["url"] === "string"
          ? item["url"]
          : typeof item["node"] === "object" && item["node"] !== null
            ? String((item["node"] as Record<string, unknown>)["snippet"] ?? "")
            : "";

      const wastedBytes =
        typeof item["wastedBytes"] === "number" ? Math.round(item["wastedBytes"]) : 0;

      const wastedKb = Math.round(wastedBytes / 1024);

      const issueMap: Record<string, string> = {
        "uses-optimized-images": "Image not optimally compressed",
        "uses-webp-images": "Image not served in a next-gen format",
        "uses-responsive-images": "Image not sized for the viewport",
        "offscreen-images": "Image loaded but not visible on initial render",
        "efficiently-encode-images": "Image encoding is inefficient",
      };

      if (url) {
        opportunities.push({
          url,
          wastedBytes,
          wastedKb,
          issue: issueMap[auditId] ?? audit.title,
        });
      }
    }
  }

  return opportunities.sort((a, b) => b.wastedBytes - a.wastedBytes);
}
