#!/usr/bin/env python3
"""E162 standalone offline verifier. Python stdlib + `cryptography` only; imports no CAIN code.
  python3 -I verify_e162_offline.py BUNDLE_DIR
Checks manifest integrity (hashes, Merkle root, Ed25519 signature), the preregistration and selection freezes, salt
commitments, recomputes every paired transfer statistic from raw_scores_public.json, checks hypothesis-verdict
consistency, negative-result preservation, public-claim consistency, and that no implementation source is bundled."""
import hashlib
import json
import math
import sys
from pathlib import Path

C = []


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


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def merkle(files):
    L = [hashlib.sha256(b"\x00" + (f + ":" + files[f]).encode()).digest() for f in sorted(files)]
    while len(L) > 1:
        L = [hashlib.sha256(b"\x01" + L[i] + (L[i + 1] if i + 1 < len(L) else L[i])).digest() for i in range(0, len(L), 2)]
    return L[0].hex() if L else hashlib.sha256(b"").hexdigest()


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 t_sf(t, df):
    x = df / (df + t * t); p = 0.5 * ibeta(df / 2, 0.5, x)
    return p if t > 0 else 1 - p


def paired(a, b):
    d = [x - y for x, y in zip(a, b)]; n = len(d); md = sum(d) / n
    sd = math.sqrt(sum((x - md) ** 2 for x in d) / (n - 1)) if n > 1 else 0.0
    p = t_sf(md / (sd / math.sqrt(n)), n - 1) if sd > 0 else (0.0 if md > 0 else 1.0)
    return round(md, 5), p


def main(argv):
    B = Path(argv[1] if len(argv) > 1 else ".")
    L = lambda n: json.loads((B / n).read_text())
    man = L("E162_MANIFEST.json")
    files = man["files"]
    present = {p.name for p in B.iterdir() if p.is_file()} - {"E162_MANIFEST.json", "MERKLE_ROOT.txt"}
    bad = [f for f, h in files.items() if not (B / f).exists() or hashlib.sha256((B / f).read_bytes()).hexdigest() != h]
    check("every manifest file present with matching SHA-256", not bad, f"{len(files)} files, bad={bad[:3]}")
    check("no unmanifested files", present <= set(files), str(sorted(present - set(files)))[:120])
    check("Merkle root recomputes", merkle(files) == man["merkle_root"] == (B / "MERKLE_ROOT.txt").read_text().strip(), man["merkle_root"][:16])
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), b"cain42.e162.manifest.v1\x1f" + canon({k: v for k, v in man.items() if k != "signature"}))
        ok = True
    except Exception:
        ok = False
    check("Ed25519 manifest signature verifies", ok, man["pubkey_fingerprint"])
    pre = (B / "E162_HYPOTHESIS_PREREGISTRATION.json").read_bytes()
    check("preregistration hash matches its freeze record", hashlib.sha256(pre).hexdigest() == L("PREREGISTRATION_FREEZE.json")["preregistration_sha256"] == man["preregistration_sha256"])
    check("selection hash matches its freeze record", hashlib.sha256((B / "selection.json").read_bytes()).hexdigest() == L("SELECTION_FREEZE.json")["selection_sha256"])
    tr = L("transfer_experiment_results.json")
    check("salt commitments match the revealed salts", all(hashlib.sha256(tr["salts_revealed"][k].encode()).hexdigest() == tr["salt_commitments"][k] for k in tr["salt_commitments"]))
    check("salt commitments were recorded before results", L("salt_commitments.json")["committed_at"] <= tr["generated_at"])
    raw = L("raw_scores_public.json")
    mism = 0; nstat = 0
    for tag, fams in raw.items():
        for arm in tr["results"][tag]:
            for f in fams:
                md, p = paired(fams[f][arm], fams[f]["G0"]); rec = tr["results"][tag][arm]["per_family_vs_G0"][f]; nstat += 1
                mism += abs(md - rec["mean_diff"]) > 1e-4 or abs(p - rec["p_one_sided_t"]) > 1e-3
            a = sum((fams[f][arm] for f in fams), []); b = sum((fams[f]["G0"] for f in fams), [])
            md, p = paired(a, b); rec = tr["results"][tag][arm]["pooled_vs_G0"]; nstat += 1
            mism += abs(md - rec["mean_diff"]) > 1e-4 or abs(p - rec["p_one_sided_t"]) > 1e-3
    check("every paired transfer statistic recomputes from raw scores", mism == 0, f"{nstat} statistics, mismatches={mism}")
    hr = L("hypothesis_results.json")["verdicts"]
    lodo = tr["results"]["sealed"]["C_lodo"]["pooled_vs_G0"]
    check("H1 verdict consistent with the sealed result", (hr["H1"]["verdict"] == "SUPPORTED") == (lodo["mean_diff"] > 0 and lodo["p_one_sided_t"] < 0.05 and hr["H1"]["p_holm"] is not None and hr["H1"]["p_holm"] < 0.05) or hr["H1"]["verdict"] == "FAILED" and lodo["mean_diff"] <= 0)
    h9 = L("h9_cladder_rewording.json"); d = h9["reworded_vs_original"]
    check("H9 drop recomputes from its accuracies", abs(d["drop_points"] - round(100 * (h9["accuracy"]["original"] - h9["accuracy"]["reworded"]), 2)) < 0.02)
    check("H9 verdict follows its preregistered rule", h9["verdict"] == ("FAILED" if d["drop_points"] > 5 and d["p_mcnemar"] < 0.05 else "SUPPORTED") == hr["H9"]["verdict"])
    sel = L("selection.json")
    check("no planted shortcut was promoted", sel["planted_selected_by_any_rule"] == 0)
    neg = {x["id"] for x in L("negative_results.json")["items"]}
    need = {k for k, v in hr.items() if v["verdict"] in ("FAILED", "INCONCLUSIVE")} | {"E161-H6/H7"}
    check("every FAILED/INCONCLUSIVE result (and E161 H6/H7) is in negative_results.json", need <= neg, str(sorted(need - neg)))
    rep = (B / "E162_FINAL_REPORT.md").read_text()
    check("final report lists every hypothesis with its verdict", all(f"| {k} | {v['verdict']} |" in rep for k, v in hr.items()))
    check("status line present; no AGI/RSI establishment claim", "AGI: NOT ESTABLISHED" in rep and "RSI: EXPERIMENTAL" in rep
          and "AGI ACHIEVED" not in rep.upper() and "RSI ESTABLISHED" not in rep.upper())
    check("external reproduction honestly marked", L("external_reproduction_status.json")["EXTERNAL_REPRODUCTION"] in ("NOT COMPLETED", "COMPLETED"))
    srcs = [f for f in files if f.endswith(".py") and f != "verify_e162_offline.py"]
    check("no implementation source in the bundle", not srcs, str(srcs))
    print(f"{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


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