"""content-c7190-000 (bravo, stage bravo_researching): read the saved primary pages, locate every figure the research
uses in its own sentence (with the section heading above it as the locator), and compute the derived numbers.
Run from this directory:  python verify_and_compute.py > verify_and_compute.out.txt
Inputs (saved 2026-09-28): gambit_report.html, ibm_newsroom_2026.html, ibm_report_page.html, csa_note.html, register.html"""
import html
import re
from pathlib import Path

HERE = Path(__file__).resolve().parent


def text_with_headings(name):
    raw = (HERE / name).read_text(encoding="utf-8", errors="replace")
    raw = re.sub(r"(?is)<(script|style|noscript)\b.*?</\1>", " ", raw)
    raw = re.sub(r"(?i)<h([1-6])[^>]*>", lambda m: "\n\n#H%s# " % m.group(1), raw)
    raw = re.sub(r"(?i)</h[1-6]>", "\n", raw)
    raw = re.sub(r"(?i)<(br|/p|/li|/tr|/div)[^>]*>", "\n", raw)
    t = html.unescape(re.sub(r"<[^>]+>", " ", raw))
    t = re.sub(r"[ \t\xa0]+", " ", t)
    return re.sub(r"\n\s*\n+", "\n", t)


def locate(name, needle, width=220):
    t = text_with_headings(name)
    i = t.find(needle)
    if i < 0:
        return None
    heads = [m for m in re.finditer(r"#H\d# ([^\n]+)", t[:i])]
    head = heads[-1].group(1).strip()[:90] if heads else "(no heading above)"
    s = max(t.rfind("\n", 0, i), t.rfind(". ", 0, i))
    e = t.find("\n", i)
    return head, re.sub(r"\s+", " ", t[s + 1:e if e > 0 else i + width]).strip()[:width * 2]


CHECKS = [
    ("gambit_report.html", "7,005.71"), ("gambit_report.html", "12,000"), ("gambit_report.html", "25.46"),
    ("gambit_report.html", "3.13"), ("gambit_report.html", "79.31"), ("gambit_report.html", "101"),
    ("gambit_report.html", "600,000"), ("gambit_report.html", "two companies"), ("gambit_report.html", "105"),
    ("gambit_report.html", "27"), ("gambit_report.html", "146"), ("gambit_report.html", "633"),
    ("gambit_report.html", "1,951"), ("gambit_report.html", "121"), ("gambit_report.html", "opus"),
    ("gambit_report.html", "GLM"), ("gambit_report.html", "DeepSeek"), ("gambit_report.html", "488,372"),
    ("gambit_report.html", "196"), ("gambit_report.html", "180 tables"), ("gambit_report.html", "19 of them"),
    ("gambit_report.html", "less than a day"), ("gambit_report.html", "staging server"), ("gambit_report.html", "Shadowserver"),
    ("ibm_newsroom_2026.html", "4.99 million"), ("ibm_newsroom_2026.html", "$6 million"),
    ("ibm_newsroom_2026.html", "One in four"), ("ibm_newsroom_2026.html", "602 organizations"),
    ("ibm_newsroom_2026.html", "Ponemon"), ("ibm_report_page.html", "model inversion"), ("ibm_report_page.html", "per record"),
]


def main():
    print("== LOCATED FIGURES (file | needle | section heading above it | the sentence)")
    for f, n in CHECKS:
        r = locate(f, n)
        print("%-24s | %-16s | %s" % (f, n, "NOT FOUND" if r is None else "%s | %s" % r))

    print("\n== CARDS BY COUNTRY (Gambit, 'Exfiltrated Data' table), sum and share check")
    rows = {"United States": 488372, "United Arab Emirates": 13559, "Saudi Arabia": 6785, "United Kingdom": 6522,
            "New Zealand": 5710, "Ireland": 5483, "Singapore": 5305, "Kuwait": 4676, "Australia": 4672,
            "Hong Kong": 4459, "France": 4295, "Qatar": 4075, "Remaining 196 countries": 64025}
    t = text_with_headings("gambit_report.html")
    for k, v in rows.items():
        print("  %-24s %8d  in page: %s" % (k, v, "{:,}".format(v) in t))
    total = sum(rows.values())
    print("  TOTAL %d; US share %.1f%%" % (total, 100.0 * rows["United States"] / total))

    print("\n== DERIVED (the attacker's side)")
    spend, lo, hi, scans, per_scan = 7005.71, 12000, 18000, 101, 25.46
    print("  per card on the metered spend: $%.4f  (= %.2f cents)" % (spend / total, 100 * spend / total))
    print("  per card on the projected total: $%.4f - $%.4f (= %.2f - %.2f cents)" % (lo / total, hi / total, 100 * lo / total,
                                                                                    100 * hi / total))
    print("  101 completed scans x $25.46 = $%.2f (scan spend inside the metered $7,005.71)" % (scans * per_scan))
    print("\n== DERIVED (against IBM 2026, primary-verified figures only)")
    print("  metered spend / one average AI-enabled breach ($6,000,000): %.3f%%" % (100 * spend / 6e6))
    print("  projected high ($18,000) / $6,000,000: %.2f%%" % (100 * hi / 6e6))
    print("  one average AI-enabled breach buys %.0f campaigns at the metered spend, %.0f at the projected high"
          % (6e6 / spend, 6e6 / hi))
    print("\n== MODEL LIFECYCLE (anthropic_model_deprecations.md, 'Model status' table; openrouter_models.json)")
    import json
    import time
    dep = (HERE / "anthropic_model_deprecations.md").read_text(encoding="utf-8")
    for ln_no, ln in enumerate(dep.splitlines(), 1):
        if re.match(r"\|\s*claude-opus-", ln):
            print("  line %3d: %s" % (ln_no, re.sub(r"\s+", " ", ln).strip()))
    models = {m["id"]: m for m in json.loads((HERE / "openrouter_models.json").read_text(encoding="utf-8"))["data"]}
    print("  OpenRouter listing (created = listing date, UTC; price per million tokens in/out):")
    for mid in ("anthropic/claude-opus-4.5", "anthropic/claude-opus-4.6", "anthropic/claude-opus-4.7", "anthropic/claude-opus-4.8",
                "anthropic/claude-opus-5", "anthropic/claude-opus-5.5", "z-ai/glm-5.2", "deepseek/deepseek-v4-pro",
                "deepseek/deepseek-v4.1-flash"):
        m = models.get(mid)
        if not m:
            print("    %-30s NOT LISTED" % mid)
            continue
        p = m.get("pricing") or {}
        print("    %-30s listed %s  $%.2f / $%.2f" % (mid, time.strftime("%Y-%m-%d", time.gmtime(m.get("created") or 0)),
                                                     float(p.get("prompt") or 0) * 1e6, float(p.get("completion") or 0) * 1e6))
    print("  Opus versions listed on OpenRouter before the campaign's Cairn week (10 Sep 2026): %s" % ", ".join(
        sorted(k.split("/")[1] for k, m in models.items() if k.startswith("anthropic/claude-opus-") and ":" not in k
               and (m.get("created") or 0) < 1789000000)))

    print("\n== SECONDARY ONLY (primary gated behind IBM's form; NOT verified here): $192 per customer-PII record")
    print("  if taken as reported: one card record at $192 vs %.2f cents to steal it = %.0fx" % (100 * spend / total,
                                                                                                 192 / (spend / total)))


if __name__ == "__main__":
    main()
