#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E156 evidence bundle (Python standard library only, no CAIN code).
    python3 -I verify_e156_offline.py <bundle_dir>
Checks integrity, the order preregistration -> forecast -> salt -> rows, every row signature, and recomputes the primary
verdict with independent code, then re-runs the preregistered (hash-frozen) analysis and compares all of it.
Passing shows internal consistency; it does not prove the scientific claim and is not an outside review.
The primary, S1-S4 and every per-family row are recomputed here with separate code (same seeds for the bootstrap). Keys are self-generated: integrity, not identity.
Timestamps are self-asserted; git commits 34debab8a (preregistration) and b5e1abd91 (forecast) are the outside order record.
The frozen bootstrap (20,000 resamples) and 4,320 pure-Python signature checks take several minutes."""
import hashlib, json, math, random, sys
from collections import defaultdict
from pathlib import Path

# ---------- Ed25519 verification (RFC 8032 §6 reference, verify only) ----------
_p = 2 ** 255 - 19
_q = 2 ** 252 + 27742317777372353535851937790883648493
_d = -121665 * pow(121666, _p - 2, _p) % _p
_I = pow(2, (_p - 1) // 4, _p)


def _inv(x):
    return pow(x, _p - 2, _p)


def _xrecover(y):
    xx = (y * y - 1) * _inv(_d * y * y + 1)
    x = pow(xx, (_p + 3) // 8, _p)
    if (x * x - xx) % _p:
        x = x * _I % _p
    return _p - x if x % 2 else x


_By = 4 * _inv(5) % _p
_B = (_xrecover(_By), _By, 1, _xrecover(_By) * _By % _p)


def _add(P, Q):
    A = (P[1] - P[0]) * (Q[1] - Q[0]) % _p
    B = (P[1] + P[0]) * (Q[1] + Q[0]) % _p
    C = 2 * P[3] * Q[3] * _d % _p
    D = 2 * P[2] * Q[2] % _p
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _p, G * H % _p, F * G % _p, E * H % _p)


def _mul(s, P):
    Q = (0, 1, 1, 0)
    while s:
        if s & 1:
            Q = _add(Q, P)
        P, s = _add(P, P), s >> 1
    return Q


def _eq(P, Q):
    return (P[0] * Q[2] - Q[0] * P[2]) % _p == 0 and (P[1] * Q[2] - Q[1] * P[2]) % _p == 0


def _decode(b):
    y = int.from_bytes(b, "little") & ((1 << 255) - 1)
    if y >= _p:
        raise ValueError
    x = _xrecover(y)
    if (x & 1) != (b[31] >> 7):
        x = _p - x
    P = (x, y, 1, x * y % _p)
    if (-x * x + y * y - 1 - _d * x * x * y * y) % _p:
        raise ValueError
    return P


def ed25519_verify(pub_hex, msg, sig_hex):
    try:
        pk, sig = bytes.fromhex(pub_hex), bytes.fromhex(sig_hex)
        A, R = _decode(pk), _decode(sig[:32])
        s = int.from_bytes(sig[32:], "little")
        if s >= _q:
            return False
        h = int.from_bytes(hashlib.sha512(sig[:32] + pk + msg).digest(), "little") % _q
        return _eq(_mul(s, _B), _add(R, _mul(h, A)))
    except Exception:
        return False



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


sha = lambda b: hashlib.sha256(b).hexdigest()
CHECKS = []


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


def merkle(files):
    L = [bytes.fromhex(sha((f + ":" + files[f]).encode())) for f in sorted(files)]
    while len(L) > 1:
        L = [hashlib.sha256(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()


def unsigned(d, *drop):
    return canon({k: v for k, v in d.items() if k not in drop}).encode()


def primary(rows):
    T = defaultdict(dict)
    for r in rows:
        if r["family"] == "bool":
            T[r["problem"]][r["arm"]] = r
    P = [(x["D2"], x["G0"]) for x in T.values() if "D2" in x and "G0" in x]; n = len(P)
    w = sum(a["research_used"] < b["research_used"] for a, b in P); l = sum(a["research_used"] > b["research_used"] for a, b in P)
    p = sum(math.comb(w + l, k) for k in range(w, w + l + 1)) / 2 ** (w + l) if w + l else 1.0
    d = [int(a["discovery"]) - int(b["discovery"]) for a, b in P]; m = sum(d) / n
    se = math.sqrt(sum((x - m) ** 2 for x in d) / (n - 1) / n); lo, hi = m - 1.959964 * se, m + 1.959964 * se
    return n, w, l, p, m, lo, hi, ("REPLICATED" if p < 0.05 and lo > -0.05 else "NOT_REPLICATED" if p >= 0.05 or hi < -0.05 else "INCONCLUSIVE")


UNF = ("bool_F4", "thr", "bool_F7")


def holm(ps):
    o = sorted(range(len(ps)), key=lambda i: ps[i]); adj = [0.0] * len(ps); run = 0.0
    for r, i in enumerate(o):
        run = max(run, min(1.0, (len(ps) - r) * ps[i])); adj[i] = run
    return adj


def table(rows, fams):
    T = defaultdict(dict)
    for r in rows:
        if r["family"] in fams:
            T[(r["family"], r["problem"])][r["arm"]] = r
    return [T[k] for k in sorted(T)]


def tail(w, l):
    n = w + l
    return sum(math.comb(n, k) for k in range(w, n + 1)) / 2 ** n if n else 1.0


def repl(rows, fams):
    P = [(x["D2"], x["G0"]) for x in table(rows, fams)]; n = len(P); d = [int(a["discovery"]) - int(b["discovery"]) for a, b in P]; m = sum(d) / n
    w = sum(a["research_used"] < b["research_used"] for a, b in P); l = sum(a["research_used"] > b["research_used"] for a, b in P); p = tail(w, l)
    se = math.sqrt(sum((x - m) ** 2 for x in d) / (n - 1) / n); lo, hi = m - 1.959964 * se, m + 1.959964 * se
    return {"n": n, "uses_less": w, "uses_more": l, "p_uses_less": p, "diff": m, "lo": lo, "hi": hi, "verdict": "REPLICATED" if p < 0.05 and lo > -0.05 else "NOT_REPLICATED" if p >= 0.05 or hi < -0.05 else "INCONCLUSIVE"}


def same_repl(x, q):
    return (x["n"], x["uses_less"], x["uses_more"], x["verdict"]) == (q["n"], q["uses_less"], q["uses_more"], q["verdict"]) and abs(x["diff"] - q["diff"]) < 1e-9 and abs(x["lo"] - q["ci95"][0]) < 1e-9 and abs(x["hi"] - q["ci95"][1]) < 1e-9


def boot(rows, b, seed=156, B=20000):
    T = table(rows, ("bool",)); n = len(T); D = [(int(x["D2"]["discovery"]), x["D2"]["research_used"], int(x[b]["discovery"]), x[b]["research_used"]) for x in T]
    def diff(idx):
        s = [0, 0, 0, 0]
        for i in idx:
            e = D[i]; s[0] += e[0]; s[1] += e[1]; s[2] += e[2]; s[3] += e[3]
        return (1000 * s[0] / s[1] if s[1] else 0.0) - (1000 * s[2] / s[3] if s[3] else 0.0)
    rnd = random.Random(seed); le = sum(diff([rnd.randrange(n) for _ in range(n)]) <= 0 for _ in range(B))
    return diff(range(n)), (le + 1) / (B + 1)


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else "."); J = lambda p: json.loads((B / p).read_text())
    man = J("MANIFEST.json")
    check("every file matches its SHA-256 and none is extra", all((B / f).exists() and sha((B / f).read_bytes()) == h for f, h in man["files"].items())
          and all(str(p.relative_to(B)) in man["files"] for p in B.rglob("*") if p.is_file() and p.name not in ("MANIFEST.json", "MERKLE_ROOT.txt") and "__pycache__" not in str(p)), f"{len(man['files'])} files")
    check("Merkle root recomputes", merkle(man["files"]) == man["merkle_root"] == (B / "MERKLE_ROOT.txt").read_text().strip())
    check("manifest signature (Ed25519)", ed25519_verify(man["bundle_pubkey_ed25519"], unsigned(man, "signature"), man["signature"]))
    pre, run, com, fc = J("preregistration.json"), J("raw/run.json"), J("raw/salt_commitment.json"), J("forecast.json")
    check("preregistration hash recomputes", sha(unsigned(pre, "preregistration_hash")) == pre["preregistration_hash"], pre["preregistration_hash"][:16])
    check("order: preregistration < forecast < salt commitment < finish", pre["preregistered_at"] < fc["made_at"] < com["committed_at"] < run["finished_at"])
    check("forecast hash recomputes and cites this preregistration", sha(json.dumps(fc["forecast"], sort_keys=True, separators=(",", ":")).encode()) == fc["forecast_sha256"] and fc["preregistration_hash"] == pre["preregistration_hash"])
    check("salt commitment and run cite this preregistration and the same frozen treatments", com["preregistration_hash"] == run["preregistration_hash"] == pre["preregistration_hash"] and com["chains_sha256"] == run["chains_sha256"] == pre["treatments"]["chains_sha256"] and not com["reproduction_run"])
    check("revealed salt matches the prior commitment", sha(bytes.fromhex(run["salt_hex_revealed_after_signing"])) == com["salt_sha256"] == run["salt_sha256"])
    check("run record signed by the evaluator key", ed25519_verify(run["evaluator_pubkey_ed25519"], unsigned(run, "signature"), run["signature"]))
    raw = (B / "raw/rows.jsonl").read_bytes(); rows = [json.loads(x) for x in raw.decode().splitlines()]
    good = sum(ed25519_verify(run["evaluator_pubkey_ed25519"], unsigned(r, "signature"), r["signature"]) for r in rows)
    check("rows bound to the run and every row signed", sha(raw) == run["rows_sha256"] and good == len(rows) == run["rows"], f"{good}/{len(rows)}")
    D = pre["design"]["confirmatory"]; want = {(f, i, a) for f, n in D["families"].items() for i in range(n) for a in D["arms"]}
    got = [(r["family"], r["problem"], r["arm"]) for r in rows]
    check("design complete: every preregistered problem x arm exactly once", len(got) == len(set(got)) and set(got) == want, f"{len(got)} rows")
    check("every run stayed within the preregistered research cap", all(0 <= r["research_used"] <= pre["budgets"]["research_cap"] for r in rows), f"max {max(r['research_used'] for r in rows)}")
    an = J("analysis.json"); n, w, l, p, m, lo, hi, v = primary(rows); q = an["primary"]
    check("primary verdict recomputed with independent code", (n, w, l, v) == (q["n"], q["uses_less"], q["uses_more"], q["verdict"]) and abs(m - q["diff"]) < 1e-9 and abs(lo - q["ci95"][0]) < 1e-9 and abs(hi - q["ci95"][1]) < 1e-9 and abs(p - q["p_uses_less"]) < 1e-9, f"{v} uses fewer {w}/{n}, rate diff {m:+.4f} [{lo:+.4f}, {hi:+.4f}]")
    check("every per-family row recomputed", all(same_repl(repl(rows, (f,)), q) for f, q in an["per_family_replication"].items()) and set(an["per_family_replication"]) == set(D["families"]))
    sec = an["secondary"]; (d1, p1), (d4, p4) = boot(rows, "G0"), boot(rows, "B3"); s3 = repl(rows, UNF); T = table(rows, ("bool",))
    x = sum(bool(t["D2"]["false_promotion"]) and not t["G0"]["false_promotion"] for t in T); y = sum(bool(t["G0"]["false_promotion"]) and not t["D2"]["false_promotion"] for t in T); p2 = tail(y, x)
    adj = holm([p1, p2, s3["p_uses_less"] if s3["verdict"] == "REPLICATED" else 1.0, p4])
    res = {"S1": adj[0] < 0.05 and d1 > 0, "S2": adj[1] < 0.05 and x < y, "S3": adj[2] < 0.05 and s3["verdict"] == "REPLICATED", "S4": adj[3] < 0.05 and d4 > 0}
    check("S1-S4 recomputed (bootstrap, McNemar, replication, Holm)", abs(d1 - sec["S1"]["diff"]) < 1e-9 and abs(p1 - sec["S1"]["p_one_sided"]) < 1e-9 and abs(d4 - sec["S4"]["diff"]) < 1e-9 and abs(p4 - sec["S4"]["p_one_sided"]) < 1e-9
          and (x, y) == (sec["S2"]["a_only"], sec["S2"]["b_only"]) and same_repl(s3, sec["S3"]) and all((sec[k]["result"] == "SUPPORTED") == v for k, v in res.items()) and all(abs(q - sec[k]["holm_p"]) < 1e-9 for q, k in zip(adj, ("S1", "S2", "S3", "S4"))), str({k: sec[k]["result"] for k in res}))
    s = J("e156-snapshot.json")
    check("snapshot cites this preregistration, the recomputed verdict and status", s["preregistration_hash"] == pre["preregistration_hash"] and s["primary"] == an["primary"] and {k: x["result"] for k, x in s["secondary"].items()} == {k: x["result"] for k, x in an["secondary"].items()} and s["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    b = []
    for f, x in fc["forecast"].items():
        a = an["per_family_replication"][f]; b.append((x["p_replicated"] - (a["verdict"] == "REPLICATED")) ** 2)
    check("forecast score recomputes", abs(s["forecast_score"]["brier"] - sum(b) / len(b)) < 1e-6)
    check("no research source in the bundle", sorted(x.name for x in B.rglob("*.py")) == ["verify_e156_offline.py", "verify_tamper_e156.py"])
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks passed"); sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()
