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

const MAX_RESOURCES = 10;

export function extractRenderBlockingResources(
  psiResponse: PsiResponse,
): RenderBlockingResource[] {
  const audit = psiResponse.lighthouseResult.audits["render-blocking-resources"];
  if (!audit?.details?.items) return [];

  const resources: RenderBlockingResource[] = [];

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

    const url = typeof item["url"] === "string" ? item["url"] : null;
    const wastedMs =
      typeof item["wastedMs"] === "number"
        ? Math.round(item["wastedMs"])
        : typeof item["totalBytes"] === "number"
          ? 0
          : 0;

    if (!url) continue;

    let resourceType: RenderBlockingResource["resourceType"] = "other";
    if (/\.js(\?|$)/i.test(url)) resourceType = "script";
    else if (/\.css(\?|$)/i.test(url)) resourceType = "stylesheet";

    resources.push({ url, wastedMs, resourceType });
  }

  return resources.sort((a, b) => b.wastedMs - a.wastedMs);
}
