"""Čtecí inventura textů a metadat aktuálních prototypů. Bez sítě a bez změn UI."""
from datetime import datetime, timezone
from hashlib import sha256
from html.parser import HTMLParser
from pathlib import Path
import json
import re

ROOT = Path(__file__).resolve().parents[4]
OUT = Path(__file__).with_name("source-copy-audit.json")
TRAVEL = "site/versions/travel-0.21.2/index.html"
URAZ = "releases/uraz/ferda-0.14.1/index.html"


class Head(HTMLParser):
    def __init__(self):
        super().__init__()
        self.meta = {}
        self.canonical = []

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "meta" and "name" in a:
            self.meta[a["name"]] = a.get("content")
        if tag == "link" and a.get("rel") == "canonical":
            self.canonical.append(a.get("href"))


def line_of(text, value):
    index = text.find(value)
    return None if index < 0 else text.count("\n", 0, index) + 1


needles = {
    TRAVEL: ["22 variant od 11 pojišťoven", "Bez telefonního spamu.",
             'name="phone"', "Telefon použijeme pouze", "Návrh jsme poslali",
             "Platbu zpracuje platební brána GoPay.", "Pojištění je sjednáno",
             "Analyzovaný plán cesty", "AI poradce", "Další pojištění se slevou 5 %"],
    URAZ: ["sjednejte pojištění online.", 'name="description"', "Kroky sjednání"],
    "releases/uraz/ferda-0.14.1/experience.js": ["Vaše kontaktní údaje", "Bez telefonního spamu.",
        "Vybrat krytí", "Pokračovat na osobní údaje", "Sestavte si svou ochranu"],
    "releases/uraz/ferda-0.14.1/ferda-flow.js": ["Konfigurace", "Rekapitulace pojištění", "Vše je připravené",
        "requiresCodebookMapping:true", "pendingIntegration:", "illustrativeQuestionnaire:"],
    "releases/uraz/ferda-0.14.1/shared/ui.js": ['autocomplete="email" inputmode="email" required',
        'autocomplete="tel" inputmode="tel"', "function heading", "replace(/modelov"],
    "releases/uraz/ferda-0.14.1/shared/core.js": ["function profileErrors", "function price", "sessionStorage.setItem"],
    "site/preview-guard.js": ["window.CEPO_TRAVEL_PREVIEW = true", "window.fetch =", "event.preventDefault()"],
    "site/versions/travel-0.21.2/assets/app.js": ["actionButton('Sjednat'", "actionButton('Sjednat tuto variantu'",
        "setText('#results-count-heading'", "function handleGopayPayment"],
    "site/versions/travel-0.21.2/assets/innovation.js": ["function previewDnaAnalysis", "window.CEPO_TRAVEL_PREVIEW", "Vysvětlit tuto nabídku podle mé cesty"],
    "site/versions/travel-0.21.2/assets/travel-navigation.js": ["const phases=", "const screens=", "const finished="],
}

result = {"created_utc": datetime.now(timezone.utc).isoformat(),
          "method": "Čtení zdrojů; neprokazuje síťové hlavičky, indexaci Googlu ani vykreslenou viditelnost.",
          "files": {}}
for relative, phrases in needles.items():
    raw = (ROOT / relative).read_bytes()
    source = raw.decode("utf-8-sig")
    facts = {"sha256": sha256(raw).hexdigest(), "bytes": len(raw), "phrases": []}
    for phrase in phrases:
        facts["phrases"].append({"text": phrase, "line": line_of(source, phrase), "present": phrase in source})
    if relative in (TRAVEL, URAZ):
        parser = Head()
        parser.feed(source.split("</head>", 1)[0])
        facts["metadata"] = parser.meta
        facts["canonical"] = parser.canonical
    result["files"][relative] = facts

travel_source = (ROOT / TRAVEL).read_text(encoding="utf-8-sig")
data = json.loads(re.search(r"window\.CEPO_TRAVEL_DATA = (.*?);</script>", travel_source, re.S).group(1))
offers = data.get("offers", {})
offer_values = list(offers.values()) if isinstance(offers, dict) else offers
result["travel_local_catalog"] = {
    "offer_count": len(offer_values),
    "insurer_group_count": len(data.get("insurerGroups", {})),
    "distinct_offer_insurer_ids": sorted({offer.get("insurerId", "") for offer in offer_values}),
    "meaning": "Pouze vložený modelový katalog. Není důkazem aktuální obchodní nabídky nebo platnosti cen a podmínek.",
}
OUT.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"output": str(OUT), "travel_local_catalog": result["travel_local_catalog"],
                  "missing_needles": [(path, p["text"]) for path, f in result["files"].items()
                                      for p in f["phrases"] if not p["present"]]}, ensure_ascii=False, indent=2))
