#!/usr/bin/env python3
"""E173 standalone offline verifier (standard library; `cryptography` only for Ed25519). Imports no CAIN code.
usage: python3 -I verify_e173_offline.py <bundle_dir>
Checks: manifest/Merkle/signature; data files match the frozen data manifest; preregistration precedes the run;
every MATH row re-scored from its prediction and the official answer with a separately written normaliser; the selected
process is exactly the development-accuracy argmax (tie rules) — no hand-picking; H1/H2/H3/H4 recomputed (paired t,
exact McNemar); Holm; API spend within the $2.50 ceiling. HumanEval pass/fail comes from the official hidden tests run in
the sandbox at experiment time; reviewers can re-run them from the frozen commit."""
import hashlib
import json
import math
import re
import sys
from pathlib import Path

C = []


def check(n, ok, d=""):
    C.append(bool(ok))
    print(("PASS " if ok else "FAIL ") + n + (f"  [{d}]" if d else ""))


def jl(p):
    return [json.loads(x) for x in Path(p).read_text().splitlines() if x.strip()]


def merkle(h):
    L = sorted(h)
    while len(L) > 1:
        if len(L) % 2:
            L.append(L[-1])
        L = [hashlib.sha256((L[i] + L[i + 1]).encode()).hexdigest() for i in range(0, len(L), 2)]
    return L[0] if L else hashlib.sha256(b"").hexdigest()


def norm(a):
    if a is None:
        return None
    a = str(a).strip().strip("$").strip()
    for x, y in (("\\left", ""), ("\\right", ""), ("\\!", ""), ("dfrac", "frac"), ("tfrac", "frac"), ("^\\circ", ""), ("^{\\circ}", ""), ("\\%", ""),
                 ("\\$", ""), (" ", ""), ("\\,", ""), ("{,}", ""), ("\\text{}", "")):
        a = a.replace(x, y)
    a = a.rstrip(".")
    m = re.fullmatch(r"\\frac\{(-?\d+)\}\{(\d+)\}", a) or re.fullmatch(r"(-?\d+)/(\d+)", a)
    if m and int(m.group(2)):
        return f"{int(m.group(1)) / int(m.group(2)):.6f}"
    try:
        return f"{float(a.replace(',', '')):.6f}"
    except ValueError:
        return a


def betacf(a, b, x):
    qab, qap, qam, c, d = a + b, a + 1, a - 1, 1.0, 1 - (a + b) * x / (a + 1)
    d = 1 / (d if abs(d) > 1e-300 else 1e-300)
    h = d
    for m in range(1, 300):
        m2 = 2 * m
        for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))):
            d = 1 + aa * d
            d = 1 / (d if abs(d) > 1e-300 else 1e-300)
            c = 1 + aa / c
            c = c if abs(c) > 1e-300 else 1e-300
            h *= d * c
    return h


def ibeta(a, b, x):
    if x <= 0:
        return 0.0
    if x >= 1:
        return 1.0
    lb = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1 - x)
    return math.exp(lb) * betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1 - math.exp(lb) * betacf(b, a, 1 - x) / b


def paired(x, y):
    d = [a - b for a, b in zip(x, y)]
    n = len(d)
    m = sum(d) / n
    sd = math.sqrt(sum((v - m) ** 2 for v in d) / (n - 1)) if n > 1 else 0.0
    if sd > 0:
        t = m / (sd / math.sqrt(n))
        p = 0.5 * ibeta((n - 1) / 2, 0.5, (n - 1) / (n - 1 + t * t))
        p = p if t > 0 else 1 - p
    else:
        p = 0.0 if m > 0 else 1.0
    return m, p


def main(argv):
    B = Path(argv[1] if len(argv) > 1 else ".")
    man = json.loads((B / "E173_MANIFEST.json").read_text())
    bad = [f for f, h in man["files"].items() if not (B / f).exists() or hashlib.sha256((B / f).read_bytes()).hexdigest() != h]
    check("manifest_file_hashes", not bad, f"{len(man['files'])} files")
    extra = [str(p.relative_to(B)) for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in set(man["files"]) | {"E173_MANIFEST.json", "PUBLICATION.json"}]
    check("no_unlisted_files", not extra, ",".join(extra[:3]))
    check("merkle_root", merkle(list(man["files"].values())) == man["merkle_root"])
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        body = {k: v for k, v in man.items() if k != "signature"}
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), json.dumps(body, sort_keys=True, separators=(",", ":")).encode())
        check("ed25519_signature", True)
    except Exception as e:  # noqa: BLE001
        check("ed25519_signature", False, type(e).__name__)
    dm = json.loads((B / "data/DATA_MANIFEST.json").read_text())
    ok = all(hashlib.sha256((B / f"data/{k}.json").read_bytes()).hexdigest() == v["sha256"] for k, v in dm["splits"].items())
    check("data_matches_frozen_manifest", ok)
    frz = json.loads((B / "E173_PREREGISTRATION_FREEZE.json").read_text())
    rec = json.loads((B / "raw/record.json").read_text())
    check("preregistration_before_run", hashlib.sha256((B / "E173_PREREGISTRATION.json").read_bytes()).hexdigest() == frz["preregistration_sha256"] and frz["frozen_at"] <= rec["started_at"],
          f"{frz['frozen_at']} <= {rec['started_at']}")
    rows = jl(B / "raw/rows.jsonl")
    gold = {p["id"]: p["answer"] for k in ("math_dev", "math_sealed", "math_replication") for p in json.loads((B / f"data/{k}.json").read_text())}
    mism = [r for r in rows if r["domain"] == "math" and ((r["pred"] is not None and norm(r["pred"]) == norm(gold[r["id"]])) != r["correct"])]
    check("math_rows_rescored", not mism, f"{sum(1 for r in rows if r['domain'] == 'math')} rows, {len(mism)} mismatches")
    over = [r for r in rows + [x for f in ("aime/rows.jsonl", "software/rows.jsonl") if (B / f).exists() for x in jl(B / f)] if r["calls"] > 2]
    check("call_cap_respected", not over, f"{len(over)} problems over 2 calls")
    sel_ok = True
    for dom, d in rec["domains"].items():
        k0 = "|".join(f"{k}={d['theta0'][k]}" for k in sorted(d["theta0"]))
        best = max(d["dev_scores"], key=lambda s: (s["dev_accuracy"], -s["mean_calls"], "|".join(f"{k}={s['theta'][k]}" for k in sorted(s["theta"])) == k0))
        sel_ok &= best["theta"] == d["theta_star"]
    check("selection_is_dev_argmax", sel_ok, "theta* = highest development accuracy (ties: fewer calls, then theta0)")
    A = json.loads((B / "E173_STATISTICAL_ANALYSIS.json").read_text())
    for h, (dom, sa, sb) in {"H1": ("math", "sealed:theta_star", "sealed:theta0"), "H2": ("code", "sealed:theta_star", "sealed:theta0"),
                             "H3_math": ("math", "sealed:theta_star", "sealed:theta_random"), "H3_code": ("code", "sealed:theta_star", "sealed:theta_random"),
                             "H4_math": ("math", "replication:theta_star", "replication:theta0"), "H4_code": ("code", "replication:theta_star", "replication:theta0")}.items():
        a = {r["id"]: r["correct"] for r in rows if r["domain"] == dom and r["split"] == sa}
        b = {r["id"]: r["correct"] for r in rows if r["domain"] == dom and r["split"] == sb}
        ks = sorted(set(a) & set(b))
        m, p = paired([float(a[k]) for k in ks], [float(b[k]) for k in ks])
        pub = A["hypotheses"][h]
        good = abs(m - pub.get("mean_diff", 0)) < 1e-6 and (abs(p - pub.get("p_one_sided", 1)) < 1e-4 or (p < 1e-9 and pub.get("p_one_sided", 1) < 1e-9))
        check(f"recomputed_{h}", good, f"{m:+.4f} n {len(ks)} p {p:.3g}")
    if (B / "aime/rows.jsonl").exists():
        ar = jl(B / "aime/rows.jsonl")
        ag = {p["id"]: p["answer"] for p in json.loads((B / "aime/aime_problems.json").read_text())}
        ap = json.loads((B / "aime/E173_AIME_PREREGISTRATION.json").read_text())
        check("aime_data_hash", hashlib.sha256((B / "aime/aime_problems.json").read_bytes()).hexdigest() == ap["data"]["sha256"], f"{len(ag)} AIME 2024/2025 problems")
        check("aime_theta_frozen_before", ap["processes"]["theta_star"] == rec["domains"]["math"]["theta_star"] and json.loads((B / "aime/E173_AIME_FREEZE.json").read_text())["frozen_at"] <= json.loads((B / "aime/record.json").read_text())["started_at"])
        mm = [r for r in ar if (r["pred"] is not None and norm(r["pred"]) == norm(ag[r["id"]])) != r["correct"]]
        check("aime_rows_rescored", not mm, f"{len(ar)} rows")
        rows_extra = [("H5_aime", ar, "math", "aime:theta_star", "aime:theta0")]
    else:
        rows_extra = []
    if (B / "software/rows.jsonl").exists():
        sw = jl(B / "software/rows.jsonl")
        sp = json.loads((B / "software/E173_SOFTWARE_PREREGISTRATION.json").read_text())
        check("software_data_hashes", all(hashlib.sha256((B / f"software/{k}.json").read_bytes()).hexdigest() == v["sha256"] for k, v in sp["data"]["splits"].items()))
        check("software_theta_frozen_before", sp["processes"]["theta_star"] == rec["domains"]["code"]["theta_star"] and json.loads((B / "software/E173_SOFTWARE_FREEZE.json").read_text())["frozen_at"] <= json.loads((B / "software/record.json").read_text())["started_at"])
        rows_extra += [("H6_apps", sw, "apps", "apps:theta_star", "apps:theta0"), ("H7_fix", sw, "fix", "fix:theta_star", "fix:theta0")]
    for h, rr, dom, sa, sb in rows_extra:
        a = {r["id"]: r["correct"] for r in rr if r["domain"] == dom and r["split"] == sa}
        b = {r["id"]: r["correct"] for r in rr if r["domain"] == dom and r["split"] == sb}
        ks = sorted(set(a) & set(b))
        m, p = paired([float(a[k]) for k in ks], [float(b[k]) for k in ks])
        pub = A["hypotheses"][h]
        check(f"recomputed_{h}", abs(m - pub["mean_diff"]) < 1e-6 and (abs(p - pub["p_one_sided"]) < 1e-4 or (p < 1e-9 and pub["p_one_sided"] < 1e-9)), f"{m:+.4f} n {len(ks)} p {p:.3g}")
    items = sorted((v, k) for k, v in A["raw_p"].items() if v is not None)
    run, ok = 0.0, True
    for i, (v, k) in enumerate(items):
        run = max(run, min(1.0, (len(items) - i) * v))
        ok &= abs(run - A["holm"][k]) < 1e-6
    check("holm_recomputed", ok)
    led = [json.loads(x) for x in (B / "E173_API_LEDGER.jsonl").read_text().splitlines() if x.strip()]
    spent = sum(x.get("usd", 0) for x in led if x["event"] == "settle")
    check("api_spend_within_ceiling", spent <= 2.50 + 1e-9, f"${spent:.4f} of $2.50, {sum(1 for x in led if x['event'] == 'settle')} calls")
    print(f"\n{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
