"""Independently recompute the headline numbers from the published CSVs (pandas only, no DuckDB).

Usage (from the project folder):
    python code/verify.py          # expect "0 mismatches"
"""
import sys
from pathlib import Path

import pandas as pd

DATA = Path(__file__).resolve().parent.parent / "data"
PLACEHOLDER = "0.0.0-stage"


def main():
    rec = pd.read_csv(DATA / "records.csv", dtype={"package": str})
    ver = pd.read_csv(DATA / "versions.csv", dtype=str)
    weekly = pd.read_csv(DATA / "weekly_units.csv")
    comp = pd.read_csv(DATA / "week_comparison.csv").set_index("unit")
    rel = pd.read_csv(DATA / "pair_relations.csv")
    checks = []

    def check(name, got, want):
        ok = abs(float(got) - float(want)) < 0.051
        checks.append(ok)
        if not ok:
            print(f"MISMATCH {name}: recomputed {got}, published {want}")

    # weekly units
    ex = ver[ver.range_type == "exact"].merge(rec[["ghsa_id", "week"]], on="ghsa_id")
    ex["pair"] = ex.package + "@" + ex.exact_version
    first_week = rec.groupby("package").week.min()
    for _, w in weekly.iterrows():
        r = rec[rec.week == w.week]
        check(f"{w.week} records", len(r), w.records)
        check(f"{w.week} packages", r.package.nunique(), w.distinct_packages)
        check(f"{w.week} exact pairs", ex[ex.week == w.week].pair.nunique(), w.exact_pairs)
        check(f"{w.week} range-only", (r.n_exact == 0).sum(), w.records_range_only)
        check(f"{w.week} first seen", (first_week.loc[r.package.unique()] == w.week).sum(), w.packages_first_seen)
        check(f"{w.week} template", r.package.str.startswith("dowload_ebok_").sum(), w.template_records)

    # focus-week ratios
    wk = weekly.set_index("week")
    prior = ["2026-10-26", "2026-11-02", "2026-11-09"]
    for unit in ["records", "distinct_packages", "exact_pairs", "packages_first_seen", "records_excl_template"]:
        ratio = wk.loc["2026-11-16", unit] / wk.loc[prior, unit].mean()
        check(f"ratio {unit}", round(ratio, 3), comp.loc[unit, "ratio_vs_prior3"])

    # pairs: rebuild from records + versions
    multi = rec[rec.package.duplicated(keep=False)].sort_values(["published_at", "ghsa_id"])
    exact = ver[ver.range_type == "exact"].groupby("ghsa_id").exact_version.apply(set)
    counts = {}
    for pkg, g in multi.groupby("package"):
        assert len(g) == 2
        a, b = g.iloc[0], g.iloc[1]
        ea, eb = exact.get(a.ghsa_id, set()), exact.get(b.ghsa_id, set())
        if ea and not eb:
            k = "scope_widening_only"
        elif eb - ea - {PLACEHOLDER}:
            k = "complementary_versions"
        elif eb - ea:
            k = "placeholder_version_only"
        elif ea == eb:
            k = "redundant"
        else:
            k = "other"
        counts[k] = counts.get(k, 0) + 1
    published = rel.groupby("evidence_relation").pairs.sum()
    for k in set(counts) | set(published.index):
        check(f"pairs {k}", counts.get(k, 0), published.get(k, 0))

    bad = checks.count(False)
    print(f"{bad} mismatches ({len(checks)} checks)")
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()
