#!/usr/bin/env node

const rawTarget = process.argv[2] || process.env.SITE_URL || "http://127.0.0.1:8796";
const baseUrl = normalizeBaseUrl(rawTarget);
const results = [];
const isLocalTarget = /^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(baseUrl);

function normalizeBaseUrl(value) {
  const withProtocol = /^https?:\/\//.test(value) ? value : `https://${value}`;
  const url = new URL(withProtocol);
  url.pathname = "/";
  url.search = "";
  url.hash = "";
  return url.toString().replace(/\/$/, "");
}

function record(ok, label, details = "") {
  results.push({ ok, label, details });
}

async function fetchText(path) {
  const response = await fetch(`${baseUrl}${path}`, {
    headers: {
      "User-Agent": "PopMediaPreGoogleAudit/1.0"
    }
  });
  const text = await response.text();
  return {
    contentType: response.headers.get("content-type") || "",
    response,
    text
  };
}

async function fetchJson(path) {
  const { contentType, response, text } = await fetchText(path);
  if (!response.ok) {
    throw new Error(`${path} returned ${response.status}`);
  }

  try {
    return {
      contentType,
      json: JSON.parse(text)
    };
  } catch (error) {
    throw new Error(`${path} is not valid JSON: ${error.message}`);
  }
}

function expectIncludes(text, expected, label) {
  record(text.includes(expected), label, expected);
}

const clientFacingBlockedTerms = [
  "Marius",
  "Florin si Marius",
  "Florin/Marius",
  "Correct positioning",
  "Structura foloseste",
  "Structura se bazeaza",
  "Google Trends",
  "date structurate",
  "regulile Google",
  "helpful content",
  "checkout",
  "webhook",
  "active-static-demo",
  "CRM lead",
  "lead route",
  "SEO promise",
  "SEO/ranking",
  "guaranteed",
  "not a contract",
  "Sponsorul intelege mai usor oferta",
  "Pagina transforma anul",
  "Pagina arata trasee clare",
  "Pagina ajuta o firma",
  "Ce trebuie sa inteleaga sponsorul",
  "Ce trebuie sa trimita sponsorul",
  "Dovada pe care o poate folosi sponsorul"
];

function expectClientSafeText(text, label) {
  for (const term of clientFacingBlockedTerms) {
    record(!text.includes(term), `${label} avoids client-inappropriate text: ${term}`);
  }
}

function sitemapContainsPath(sitemap, path) {
  const urls = [...sitemap.matchAll(/<loc>(.*?)<\/loc>/g)].map((match) => match[1]);

  if (isLocalTarget) {
    return urls.some((url) => new URL(url).pathname === path);
  }

  return urls.includes(`${baseUrl}${path}`);
}

async function checkStatus(path, expectedType) {
  const { contentType, response, text } = await fetchText(path);
  record(response.ok, `${path} returns 200`, `status ${response.status}`);
  if (expectedType) {
    record(
      contentType.includes(expectedType),
      `${path} content type includes ${expectedType}`,
      contentType
    );
  }
  return { contentType, response, text };
}

async function run() {
  console.log(`Pop Media pre-Google audit: ${baseUrl}`);

  const htmlRoutes = [
    "/",
    "/despre",
    "/interviuri",
    "/comunitate",
    "/publicitate",
    "/evenimente",
    "/standuri",
    "/culise",
    "/caz-eveniment",
    "/media-kit",
    "/audienta",
    "/pachete",
    "/proces",
    "/potrivire",
    "/campanii",
    "/momente",
    "/dovada",
    "/intrebari",
    "/parteneri",
    "/surse",
    "/ai",
    "/brief",
    "/contact"
  ];

  for (const path of htmlRoutes) {
    const page = await checkStatus(path, "text/html");
    expectClientSafeText(page.text, path);
  }

  const home = await checkStatus("/", "text/html");
  const requiredSecurityHeaders = [
    ["content-security-policy", "frame-ancestors 'none'"],
    ["referrer-policy", "strict-origin-when-cross-origin"],
    ["x-content-type-options", "nosniff"],
    ["x-frame-options", "DENY"],
    ["cross-origin-opener-policy", "same-origin"],
    ["cross-origin-resource-policy", "same-origin"],
    ["permissions-policy", "camera=()"]
  ];

  for (const [header, expected] of requiredSecurityHeaders) {
    const value = home.response.headers.get(header) || "";
    record(
      value.includes(expected),
      `security header ${header} includes ${expected}`,
      value || "missing"
    );
  }

  const csp = home.response.headers.get("content-security-policy") || "";
  record(csp.length > 0 && csp.length < 2000, "CSP stays compact for crawlers", `${csp.length} chars`);
  record(csp.includes("'nonce-"), "CSP uses a request nonce for inline scripts", csp);
  record(csp.includes("'strict-dynamic'"), "CSP uses strict-dynamic with nonce", csp);
  record(
    !home.response.headers.has("x-powered-by"),
    "X-Powered-By header is not exposed",
    home.response.headers.get("x-powered-by") || "not present"
  );

  expectIncludes(
    home.text,
    "Pop Media pentru sponsori, evenimente si comunitatea romana din Belgia.",
    "homepage has product-led H1"
  );
  expectIncludes(
    home.text,
    "Nu cumperi doar spatiu. Cumperi prezenta care poate fi tinuta minte.",
    "homepage explains the Pop Media method"
  );
  expectIncludes(
    home.text,
    "Promovarea buna raspunde rapid la patru intrebari.",
    "homepage includes sponsor decision path"
  );
  expectIncludes(
    home.text,
    "Deschide media kit-ul pentru sponsori",
    "homepage links sponsor decision path to media kit"
  );
  expectIncludes(
    home.text,
    "Vezi audienta si contextul",
    "homepage links audience context from decision path"
  );
  expectIncludes(
    home.text,
    "Vezi harta audientei",
    "homepage links audience context section"
  );
  expectIncludes(
    home.text,
    "Vezi potrivirea pe categorii",
    "homepage links sponsor fit guide"
  );
  expectIncludes(
    home.text,
    "Vezi traseele de campanie",
    "homepage links sponsor campaign paths"
  );
  expectIncludes(
    home.text,
    "Vezi calendarul de campanie",
    "homepage links campaign moments planner"
  );
  expectIncludes(
    home.text,
    "Vezi ce poate ramane dupa campanie",
    "homepage links sponsor proof deliverables"
  );
  expectIncludes(
    home.text,
    "Vezi toate pachetele de discutie",
    "homepage links sponsor package menu"
  );
  expectIncludes(
    home.text,
    "Vezi procesul complet",
    "homepage links sponsor process"
  );
  expectIncludes(
    home.text,
    "Vezi cum lucram in culise",
    "homepage links backstage event production"
  );
  expectIncludes(
    home.text,
    "Vezi pachetele de stand",
    "homepage links event stands"
  );
  expectIncludes(
    home.text,
    "Vezi produsul de interviuri",
    "homepage links interviews product"
  );
  expectIncludes(
    home.text,
    "Vezi comunicarea comunitara",
    "homepage links community communication"
  );
  expectIncludes(
    home.text,
    "Trimite informatiile pentru oferta",
    "homepage links first offer information"
  );
  expectIncludes(home.text, "application/ld+json", "homepage includes JSON-LD");
  expectIncludes(home.text, "manifest.webmanifest", "homepage links web app manifest");
  expectIncludes(home.text, "Radio Belgia Ads", "homepage includes first business product");
  expectIncludes(home.text, "Pachet Sponsor Eveniment", "homepage includes event sponsor product");

  const interviuri = await fetchText("/interviuri");
  expectIncludes(
    interviuri.text,
    "Interviuri si continut de comunitate",
    "/interviuri has interview product title"
  );
  expectIncludes(
    interviuri.text,
    "Cinci forme de interviu care pot deveni produs",
    "/interviuri explains interview formats"
  );
  expectIncludes(
    interviuri.text,
    "Ce pregatim inainte de inregistrare",
    "/interviuri includes interview prep checklist"
  );
  expectIncludes(
    interviuri.text,
    "Unghiuri sigure pentru sponsori",
    "/interviuri includes sponsor-safe angles"
  );
  expectIncludes(
    interviuri.text,
    "Ce pregatim inainte de publicare",
    "/interviuri includes consent and publication approvals"
  );
  expectIncludes(
    interviuri.text,
    "Ce poate ramane dupa interviu",
    "/interviuri explains reusable assets"
  );
  expectIncludes(
    interviuri.text,
    "numele, functia, imaginea, vocea si citatele aprobate",
    "/interviuri includes consent and approval details"
  );

  const comunitate = await fetchText("/comunitate");
  expectIncludes(
    comunitate.text,
    "Comunicare comunitara si institutionala",
    "/comunitate has community communication title"
  );
  expectIncludes(
    comunitate.text,
    "Cinci mesaje care pot deveni produs",
    "/comunitate explains community message types"
  );
  expectIncludes(
    comunitate.text,
    "Punte de limbaj pentru Belgia",
    "/comunitate explains Belgium language bridge"
  );
  expectIncludes(
    comunitate.text,
    "Ce stabilim inainte de publicare",
    "/comunitate includes approval checklist"
  );
  expectIncludes(
    comunitate.text,
    "Ce stabilim pentru incredere",
    "/comunitate explains boundaries"
  );
  expectIncludes(
    comunitate.text,
    "sursa informatiei si rolul fiecarui partener",
    "/comunitate includes trust clarifications"
  );
  expectIncludes(
    comunitate.text,
    "recap-ul sau linkul care ramane dupa publicare",
    "/comunitate includes follow-up proof"
  );

  const publicitate = await fetchText("/publicitate");
  expectIncludes(
    publicitate.text,
    "Prezenta radio care poate continua in social si follow-up.",
    "/publicitate explains the sponsor offer"
  );
  expectIncludes(
    publicitate.text,
    "Cum te ajuta",
    "/publicitate uses nontechnical intent label"
  );
  expectIncludes(
    publicitate.text,
    "De ce Pop Media",
    "/publicitate uses plain public data label"
  );
  record(
    !publicitate.text.includes("Intentie pentru oameni si AI"),
    "/publicitate avoids technical AI-facing label"
  );
  expectIncludes(
    publicitate.text,
    "Intrebari inainte de colaborare",
    "/publicitate includes buyer questions"
  );
  expectIncludes(
    publicitate.text,
    "Alege pachetul de discutie potrivit",
    "/publicitate includes advertising package selector"
  );
  expectIncludes(
    publicitate.text,
    "Ce pregatim inainte de oferta",
    "/publicitate includes advertiser pre-call brief"
  );

  const evenimente = await fetchText("/evenimente");
  expectIncludes(
    evenimente.text,
    "Evenimentul devine o prezenta completa",
    "/evenimente explains before-during-after value"
  );

  const standuri = await fetchText("/standuri");
  expectIncludes(
    standuri.text,
    "Standuri si expozanti la evenimente",
    "/standuri has event stands title"
  );
  expectIncludes(
    standuri.text,
    "Cinci tipuri de prezenta la eveniment",
    "/standuri explains stand types"
  );
  expectIncludes(
    standuri.text,
    "Ce pregatim inainte",
    "/standuri includes setup checklist"
  );
  expectIncludes(
    standuri.text,
    "Cum pastram zona usor de inteles",
    "/standuri includes visitor-care guidance"
  );
  expectIncludes(
    standuri.text,
    "Ce poate ramane dupa stand",
    "/standuri explains proof after stand"
  );
  expectIncludes(
    standuri.text,
    "Ce stabilim inainte de eveniment",
    "/standuri explains boundaries"
  );
  expectIncludes(
    standuri.text,
    "persoana responsabila si mesajul scurt",
    "/standuri includes stand preparation details"
  );

  const culise = await fetchText("/culise");
  expectIncludes(
    culise.text,
    "Culise si productie la evenimente",
    "/culise has backstage production title"
  );
  expectIncludes(
    culise.text,
    "Cinci lucruri care se pregatesc in culise",
    "/culise includes backstage production lanes"
  );
  expectIncludes(
    culise.text,
    "Primire si orientare cu grija",
    "/culise includes reception and orientation care"
  );
  expectIncludes(
    culise.text,
    "sprijin logistic pentru organizator",
    "/culise includes organizer support guidance"
  );
  expectIncludes(
    culise.text,
    "Dovada pe care o poti folosi dupa eveniment",
    "/culise explains sponsor proof trail"
  );
  expectIncludes(
    culise.text,
    "Ce pregatim inainte de productie",
    "/culise explains backstage boundaries"
  );

  const cazEveniment = await fetchText("/caz-eveniment");
  expectIncludes(
    cazEveniment.text,
    "Exemplu de activare la eveniment",
    "/caz-eveniment has event case title"
  );
  expectIncludes(
    cazEveniment.text,
    "1 Mai Muncitoresc",
    "/caz-eveniment references public event example"
  );
  expectIncludes(
    cazEveniment.text,
    "Inainte, la fata locului si dupa eveniment",
    "/caz-eveniment explains event sponsor stages"
  );
  expectIncludes(
    cazEveniment.text,
    "exemplul se adapteaza dupa rolul si obiectivul partenerului",
    "/caz-eveniment explains adaptable sponsor model"
  );

  const mediaKit = await fetchText("/media-kit");
  expectIncludes(
    mediaKit.text,
    "Media kit pentru sponsori Pop Media",
    "/media-kit has sponsor media kit title"
  );
  expectIncludes(
    mediaKit.text,
    "Ce trebuie sa fie clar inainte de oferta",
    "/media-kit explains sponsor understanding"
  );
  expectIncludes(
    mediaKit.text,
    "Pachetele care merita discutate primele",
    "/media-kit includes package directions"
  );
  expectIncludes(
    mediaKit.text,
    "Ce cerem inainte sa pregatim oferta",
    "/media-kit includes pre-offer brief"
  );
  expectIncludes(
    mediaKit.text,
    "Vezi pachete",
    "/media-kit links package menu"
  );

  const audienta = await fetchText("/audienta");
  expectIncludes(
    audienta.text,
    "Audienta si context comunitar",
    "/audienta has audience context title"
  );
  expectIncludes(
    audienta.text,
    "Sase segmente pentru o promovare mai bine tintita",
    "/audienta includes audience segments"
  );
  expectIncludes(
    audienta.text,
    "Romani din Belgia",
    "/audienta includes Romanian community audience"
  );
  expectIncludes(
    audienta.text,
    "Ce sustine contextul public",
    "/audienta includes public evidence section"
  );
  expectIncludes(
    audienta.text,
    "Intrebari bune inainte de oferta",
    "/audienta includes sponsor questions"
  );
  expectIncludes(
    audienta.text,
    "Ce face audienta mai usor de prezentat",
    "/audienta includes audience-claim boundaries"
  );
  expectIncludes(
    audienta.text,
    "segmente de public descrise",
    "/audienta includes audience segment framing"
  );
  expectIncludes(
    audienta.text,
    "date masurate separat",
    "/audienta explains measured data handling"
  );

  const pachete = await fetchText("/pachete");
  expectIncludes(
    pachete.text,
    "Pachete Pop Media pentru sponsori",
    "/pachete has sponsor package title"
  );
  expectIncludes(
    pachete.text,
    "Cum alegem pachetul corect",
    "/pachete explains package selection"
  );
  expectIncludes(
    pachete.text,
    "Pachete care pot fi discutate",
    "/pachete includes package menu"
  );
  expectIncludes(
    pachete.text,
    "Radio + Social Follow-up",
    "/pachete includes radio social package"
  );
  expectIncludes(
    pachete.text,
    "Cum transformam pachetul in oferta",
    "/pachete explains commercial exclusions"
  );
  expectIncludes(
    pachete.text,
    "Pachetul devine concret dupa ce stim obiectivul tau",
    "/pachete explains package confirmation"
  );

  const proces = await fetchText("/proces");
  expectIncludes(
    proces.text,
    "Proces Pop Media pentru sponsori",
    "/proces has sponsor process title"
  );
  expectIncludes(
    proces.text,
    "Sase pasi simpli",
    "/proces includes process steps"
  );
  expectIncludes(
    proces.text,
    "Ce stabilim inainte de publicare",
    "/proces includes approval checklist"
  );
  expectIncludes(
    proces.text,
    "Linie editoriala si continut sponsorizat",
    "/proces explains editorial trust"
  );
  expectIncludes(
    proces.text,
    "Cum pastram propunerea clara",
    "/proces explains stop conditions"
  );
  expectIncludes(
    proces.text,
    "alegem pachetul dupa obiectiv",
    "/proces includes commercial clarity principles"
  );

  const brief = await fetchText("/brief");
  expectIncludes(
    brief.text,
    "Informatii pentru oferta Pop Media",
    "/brief has sponsor offer information title"
  );
  expectIncludes(
    brief.text,
    "Sase raspunsuri care fac oferta mai clara",
    "/brief explains six brief fields"
  );
  expectIncludes(
    brief.text,
    "Ce trebuie sa trimiti",
    "/brief includes sponsor information section"
  );
  expectIncludes(
    brief.text,
    "Daca nu stii pachetul, alege directia",
    "/brief includes package direction guidance"
  );
  expectIncludes(
    brief.text,
    "Un mesaj scurt este suficient",
    "/brief includes email model"
  );
  expectIncludes(
    brief.text,
    "Ce trebuie aprobat inainte",
    "/brief includes approval checklist"
  );
  expectIncludes(
    brief.text,
    "Ce stabilim inainte de oferta",
    "/brief includes commercial boundaries"
  );
  expectIncludes(
    brief.text,
    "perioada si canalele",
    "/brief includes offer clarification details"
  );
  expectIncludes(
    brief.text,
    "persoana care aproba mesajul final",
    "/brief includes final approval detail"
  );

  const potrivire = await fetchText("/potrivire");
  expectIncludes(
    potrivire.text,
    "Pentru cine se potriveste Pop Media",
    "/potrivire has sponsor fit title"
  );
  expectIncludes(
    potrivire.text,
    "Patru filtre simple inainte de discutie",
    "/potrivire includes decision filters"
  );
  expectIncludes(
    potrivire.text,
    "Contabili, fiscalitate si consultanta",
    "/potrivire includes sponsor business segments"
  );
  expectIncludes(
    potrivire.text,
    "Cand ajustam directia de oferta",
    "/potrivire explains offer adjustment"
  );

  const campanii = await fetchText("/campanii");
  expectIncludes(
    campanii.text,
    "Campanii Pop Media pe obiectiv",
    "/campanii has campaign objective title"
  );
  expectIncludes(
    campanii.text,
    "Patru reguli pentru o campanie sanatoasa",
    "/campanii includes campaign principles"
  );
  expectIncludes(
    campanii.text,
    "Sa fiu prezent la un eveniment romanesc",
    "/campanii includes event presence objective"
  );
  expectIncludes(
    campanii.text,
    "Dovada utila dupa",
    "/campanii explains proof after campaign"
  );
  expectIncludes(
    campanii.text,
    "Ce stabilim inainte de oferta",
    "/campanii includes pre-offer clarity"
  );

  const momente = await fetchText("/momente");
  expectIncludes(
    momente.text,
    "Momente de campanie pentru sponsori",
    "/momente has campaign moments title"
  );
  expectIncludes(
    momente.text,
    "Sapte momente in care o campanie poate avea sens",
    "/momente includes seasonal moments list"
  );
  expectIncludes(
    momente.text,
    "1 Decembrie si identitate romaneasca",
    "/momente includes Romanian identity moment"
  );
  expectIncludes(
    momente.text,
    "Cum pregatim momentul inainte",
    "/momente includes pre-campaign planning"
  );
  expectIncludes(
    momente.text,
    "Alegem canalul dupa rol",
    "/momente explains channel-role fit"
  );
  expectIncludes(
    momente.text,
    "Ce stabilim pentru momentul potrivit",
    "/momente includes campaign timing clarity"
  );
  expectIncludes(
    momente.text,
    "dovada care ramane dupa campanie",
    "/momente includes post-campaign proof planning"
  );
  record(
    !momente.text.includes("Structura foloseste"),
    "/momente avoids source-method copy in the client offer"
  );
  record(
    !momente.text.includes("Google Trends") && !momente.text.includes("date structurate"),
    "/momente avoids internal optimization copy in visible page text"
  );

  const dovada = await fetchText("/dovada");
  expectIncludes(
    dovada.text,
    "Ce ramane dupa campanie",
    "/dovada has post-campaign proof title"
  );
  expectIncludes(
    dovada.text,
    "Livrabile care pot ramane dupa campanie",
    "/dovada includes deliverables section"
  );
  expectIncludes(
    dovada.text,
    "Fisa simpla de dovada",
    "/dovada includes proof ledger"
  );
  expectIncludes(
    dovada.text,
    "Confirmare mesaj radio",
    "/dovada includes radio confirmation deliverable"
  );
  expectIncludes(
    dovada.text,
    "Ce stabilim pentru un material convingator",
    "/dovada includes proof-pack clarifications"
  );

  const intrebari = await fetchText("/intrebari");
  expectIncludes(
    intrebari.text,
    "Intrebari pentru sponsori Pop Media",
    "/intrebari has sponsor questions title"
  );
  expectIncludes(
    intrebari.text,
    "Pentru ce fel de firma are sens Pop Media?",
    "/intrebari includes fit question"
  );
  expectIncludes(
    intrebari.text,
    "Cum se confirma pachetul si bugetul?",
    "/intrebari explains no live public prices"
  );
  expectIncludes(
    intrebari.text,
    "Ce trebuie clarificat inainte de oferta?",
    "/intrebari explains commercial boundaries"
  );

  const contact = await fetchText("/contact");
  expectIncludes(
    contact.text,
    "Trimite un email pe care il putem transforma in oferta.",
    "/contact includes sponsor email brief"
  );
  expectIncludes(
    contact.text,
    "Scrie emailul de inceput",
    "/contact includes prefilled email action"
  );
  expectIncludes(
    contact.text,
    "Primul pas ramane simplu",
    "/contact explains simple first step"
  );

  const parteneri = await fetchText("/parteneri");
  expectIncludes(
    parteneri.text,
    "O prezentare clara pentru oamenii care trebuie sa spuna da.",
    "/parteneri explains the proof pack"
  );
  expectIncludes(
    parteneri.text,
    "Blueprint proof pack pentru sponsori",
    "/parteneri includes sponsor proof-pack blueprint"
  );
  expectIncludes(
    parteneri.text,
    "Ce face o colaborare mai usor de aprobat",
    "/parteneri explains sponsor decision signals"
  );

  const ai = await fetchText("/ai");
  expectIncludes(
    ai.text,
    "Cum poate fi prezentat corect Pop Media",
    "/ai includes client-facing presentation guidance"
  );
  expectIncludes(
    ai.text,
    "De ce este usor de verificat",
    "/ai explains public trust signals"
  );

  const entity = await fetchJson("/entity.json");
  record(
    entity.contentType.includes("application/json"),
    "/entity.json content type is JSON",
    entity.contentType
  );
  record(entity.json.entity?.name === "Pop Media", "/entity.json identifies Pop Media");
  record(
    Array.isArray(entity.json.businessProducts) && entity.json.businessProducts.length >= 6,
    "/entity.json includes business products"
  );
  record(
    Array.isArray(entity.json.assistantRecommendationGuide) &&
      entity.json.assistantRecommendationGuide.length >= 3,
    "/entity.json includes assistant recommendation guide"
  );
  record(
    Array.isArray(entity.json.sponsorProofPackBlueprint?.stages) &&
      entity.json.sponsorProofPackBlueprint.stages.length === 3,
    "/entity.json includes sponsor proof-pack stages"
  );
  record(
    Array.isArray(entity.json.advertisingPackageLadder) &&
      entity.json.advertisingPackageLadder.length === 3,
    "/entity.json includes advertising package ladder"
  );
  record(
    Array.isArray(entity.json.sponsorPackageMenu?.packages) &&
      entity.json.sponsorPackageMenu.packages.length >= 6,
    "/entity.json includes sponsor package menu"
  );
  record(
    Array.isArray(entity.json.sponsorCollaborationProcess?.steps) &&
      entity.json.sponsorCollaborationProcess.steps.length >= 6,
    "/entity.json includes sponsor collaboration process"
  );
  record(
    Array.isArray(entity.json.advertiserPreCallBrief) &&
      entity.json.advertiserPreCallBrief.length >= 4,
    "/entity.json includes advertiser pre-call brief"
  );
  record(
    Array.isArray(entity.json.sponsorMediaKit?.kitSections) &&
      entity.json.sponsorMediaKit.kitSections.length >= 4,
    "/entity.json includes sponsor media kit"
  );
  record(
    Array.isArray(entity.json.audienceContextMap?.audienceSegments) &&
      entity.json.audienceContextMap.audienceSegments.length >= 6,
    "/entity.json includes audience context map"
  );
  record(
    Array.isArray(entity.json.sponsorOfferBrief?.briefFields) &&
      entity.json.sponsorOfferBrief.briefFields.length >= 6,
    "/entity.json includes sponsor offer information"
  );
  record(
    Array.isArray(entity.json.sponsorFitGuide?.fitCards) &&
      entity.json.sponsorFitGuide.fitCards.length >= 6,
    "/entity.json includes sponsor fit guide"
  );
  record(
    Array.isArray(entity.json.sponsorCampaignPaths?.paths) &&
      entity.json.sponsorCampaignPaths.paths.length >= 5,
    "/entity.json includes sponsor campaign paths"
  );
  record(
    Array.isArray(entity.json.campaignMomentsPlanner?.moments) &&
      entity.json.campaignMomentsPlanner.moments.length >= 7,
    "/entity.json includes campaign moments planner"
  );
  record(
    Array.isArray(entity.json.sponsorProofDeliverables?.deliverables) &&
      entity.json.sponsorProofDeliverables.deliverables.length >= 6,
    "/entity.json includes sponsor proof deliverables"
  );
  record(
    Array.isArray(entity.json.eventProductionBackstage?.operatingLanes) &&
      entity.json.eventProductionBackstage.operatingLanes.length >= 5,
    "/entity.json includes backstage event production"
  );
  record(
    Array.isArray(entity.json.interviewContentStudio?.formats) &&
      entity.json.interviewContentStudio.formats.length >= 5,
    "/entity.json includes interview content studio"
  );
  record(
    Array.isArray(entity.json.communityCommunicationBridge?.messageTypes) &&
      entity.json.communityCommunicationBridge.messageTypes.length >= 5,
    "/entity.json includes community communication bridge"
  );
  record(
    Array.isArray(entity.json.eventStandExhibitorPack?.standTypes) &&
      entity.json.eventStandExhibitorPack.standTypes.length >= 5,
    "/entity.json includes event stand exhibitor pack"
  );
  record(
    Array.isArray(entity.json.sponsorQuestionGuide?.groups) &&
      entity.json.sponsorQuestionGuide.groups.length >= 3,
    "/entity.json includes sponsor question guide"
  );
  record(
    Array.isArray(entity.json.eventCaseStudy?.stages) &&
      entity.json.eventCaseStudy.stages.length === 3,
    "/entity.json includes event case study"
  );

  const sources = await fetchJson("/sources.json");
  record(
    Array.isArray(sources.json.sources) && sources.json.sources.length >= 4,
    "/sources.json includes public source registry"
  );

  const services = await fetchJson("/services.json");
  const serviceNames = new Set((services.json.services || []).map((service) => service.name));
  const expectedServices = [
    "Radio Belgia Ads",
    "Pachet Sponsor Eveniment",
    "Productie Media la Evenimente",
    "Interviuri si Podcasturi",
    "Proof Pack pentru Parteneri",
    "Ghid Comunitar si Trust Layer"
  ];
  for (const service of expectedServices) {
    record(serviceNames.has(service), `/services.json includes ${service}`);
  }
  record(
    services.json.futureIosReadiness?.status === "content_layer_ready",
    "/services.json includes future digital readiness"
  );
  record(
    Array.isArray(services.json.futureIosReadiness?.suggestedEntities) &&
      services.json.futureIosReadiness.suggestedEntities.length >= 4,
    "/services.json includes future digital content suggestions"
  );
  record(
    Array.isArray(services.json.servicePageOffers) &&
      services.json.servicePageOffers.length >= 3,
    "/services.json includes service page offers"
  );
  const servicesPayload = JSON.stringify(services.json);
  const internalMethodTerms = [
    "Structura foloseste",
    "Structura se bazeaza",
    "Google Trends",
    "date structurate",
    "regulile Google",
    "helpful content"
  ];
  for (const term of internalMethodTerms) {
    record(!servicesPayload.includes(term), `/services.json avoids internal method copy: ${term}`);
  }
  record(
    Array.isArray(services.json.sponsorProofPackBlueprint?.decisionSignals) &&
      services.json.sponsorProofPackBlueprint.decisionSignals.length >= 4,
    "/services.json includes sponsor proof-pack decision signals"
  );
  record(
    Array.isArray(services.json.advertisingPackageLadder) &&
      services.json.advertisingPackageLadder.some((item) => item.name === "Radio Start"),
    "/services.json includes advertising package ladder"
  );
  record(
    Array.isArray(services.json.sponsorPackageMenu?.packages) &&
      services.json.sponsorPackageMenu.packages.some((item) => item.name === "Proof Pack pentru Parteneri"),
    "/services.json includes sponsor package menu"
  );
  record(
    Array.isArray(services.json.sponsorCollaborationProcess?.steps) &&
      services.json.sponsorCollaborationProcess.steps.some((item) => item.title === "Productie si aprobare"),
    "/services.json includes sponsor collaboration process"
  );
  record(
    Array.isArray(services.json.eventProductionBackstage?.accessibilityCare) &&
      services.json.eventProductionBackstage.accessibilityCare.length >= 5,
    "/services.json includes backstage event production"
  );
  record(
    Array.isArray(services.json.interviewContentStudio?.sponsorSafeAngles) &&
      services.json.interviewContentStudio.sponsorSafeAngles.length >= 5,
    "/services.json includes interview content studio"
  );
  record(
    Array.isArray(services.json.communityCommunicationBridge?.languageBridge) &&
      services.json.communityCommunicationBridge.languageBridge.length >= 4,
    "/services.json includes community communication bridge"
  );
  record(
    Array.isArray(services.json.eventStandExhibitorPack?.visitorCare) &&
      services.json.eventStandExhibitorPack.visitorCare.length >= 5,
    "/services.json includes event stand exhibitor pack"
  );
  record(
    Array.isArray(services.json.advertiserPreCallBrief) &&
      services.json.advertiserPreCallBrief.length >= 4,
    "/services.json includes advertiser pre-call brief"
  );
  record(
    services.json.sponsorMediaKit?.title === "Media kit pentru sponsori Pop Media",
    "/services.json includes sponsor media kit"
  );
  record(
    Array.isArray(services.json.audienceContextMap?.notIncluded) &&
      services.json.audienceContextMap.notIncluded.length >= 5,
    "/services.json includes audience context map"
  );
  record(
    Array.isArray(services.json.sponsorOfferBrief?.notIncluded) &&
      services.json.sponsorOfferBrief.notIncluded.length >= 5,
    "/services.json includes sponsor offer information"
  );
  record(
    services.json.sponsorFitGuide?.title === "Pentru cine se potriveste Pop Media",
    "/services.json includes sponsor fit guide"
  );
  record(
    services.json.sponsorCampaignPaths?.title === "Campanii Pop Media pe obiectiv",
    "/services.json includes sponsor campaign paths"
  );
  record(
    Array.isArray(services.json.campaignMomentsPlanner?.channelMix) &&
      services.json.campaignMomentsPlanner.channelMix.length >= 5,
    "/services.json includes campaign moments planner"
  );
  record(
    services.json.sponsorProofDeliverables?.title === "Ce ramane dupa campanie",
    "/services.json includes sponsor proof deliverables"
  );
  record(
    services.json.sponsorQuestionGuide?.title === "Intrebari pentru sponsori Pop Media",
    "/services.json includes sponsor question guide"
  );
  record(
    services.json.eventCaseStudy?.title === "Exemplu de eveniment pentru sponsori",
    "/services.json includes event case study"
  );

  const sitemap = await checkStatus("/sitemap.xml", "application/xml");
  for (const path of [
    "/",
    "/despre",
    "/interviuri",
    "/comunitate",
    "/publicitate",
    "/evenimente",
    "/standuri",
    "/culise",
    "/caz-eveniment",
    "/media-kit",
    "/audienta",
    "/pachete",
    "/proces",
    "/potrivire",
    "/campanii",
    "/momente",
    "/dovada",
    "/intrebari",
    "/parteneri",
    "/surse",
    "/ai",
    "/brief",
    "/entity.json",
    "/sources.json",
    "/services.json"
  ]) {
    record(sitemapContainsPath(sitemap.text, path), `/sitemap.xml includes ${path}`);
  }

  const robots = await checkStatus("/robots.txt", "text/plain");
  for (const token of ["Sitemap:", "OAI-SearchBot", "GPTBot", "PerplexityBot", "ClaudeBot"]) {
    expectIncludes(robots.text, token, `/robots.txt includes ${token}`);
  }

  const llms = await checkStatus("/llms.txt", "text/plain");
  for (const token of ["Business Products", "Advertising Package Selector", "Sponsor Media Kit", "Audience And Community Context", "Sponsor Package Menu", "Sponsor Collaboration Process", "Sponsor Offer Brief", "Event Stands And Exhibitors", "Backstage Event Production", "Interview And Community Content", "Community And Institutional Communication", "Sponsor Fit Guide", "Sponsor Campaign Objective Guide", "Sponsor Campaign Moments Planner", "Sponsor Post-Campaign Proof Guide", "Sponsor Questions And Objections", "Public Event Example", "Sponsor Proof Pack Blueprint", "Assistant Recommendation Guide", "/entity.json", "/sources.json", "/services.json"]) {
    expectIncludes(llms.text, token, `/llms.txt includes ${token}`);
  }
  expectClientSafeText(llms.text, "/llms.txt");
  expectClientSafeText(JSON.stringify(entity.json), "/entity.json");
  expectClientSafeText(JSON.stringify(sources.json), "/sources.json");
  expectClientSafeText(JSON.stringify(services.json), "/services.json");

  const manifest = await fetchJson("/manifest.webmanifest");
  record(manifest.json.name?.includes("Pop Media"), "/manifest.webmanifest names Pop Media");
  record(manifest.json.display === "standalone", "/manifest.webmanifest is installable");

  const passed = results.filter((result) => result.ok).length;
  const total = results.length;
  const score = Math.round((passed / total) * 100);

  console.log("");
  for (const result of results) {
    console.log(`${result.ok ? "PASS" : "FAIL"} ${result.label}${result.details ? ` (${result.details})` : ""}`);
  }
  console.log("");
  console.log(`Score: ${score}/100 (${passed}/${total} checks passed)`);

  if (passed !== total) {
    process.exitCode = 1;
  }
}

run().catch((error) => {
  console.error(`Audit failed: ${error.message}`);
  process.exit(1);
});
