#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E150 evidence bundle.

Python standard library only: imports no CAIN code and no third-party package (Ed25519 via the RFC 8032 reference
algorithm below). Every verdict is recomputed here from the signed raw rows, independently of analyze_e150.py.

    python3 -I verify_e150_offline.py <bundle_dir>

Passing means the bundle is internally consistent and the published decisions follow from the signed data. It does
not prove the scientific claim, and it does not re-run research (that needs the agent code; see REVIEWER_KIT.md).
"""
import hashlib, json, math, 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)


def sha(b):
    return hashlib.sha256(b).hexdigest()


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


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


CHECKS = []


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


def merkle(files):
    leaves = [bytes.fromhex(sha((f + ":" + files[f]).encode())) for f in sorted(files)]
    while len(leaves) > 1:
        leaves = [hashlib.sha256(leaves[i] + (leaves[i + 1] if i + 1 < len(leaves) else leaves[i])).digest() for i in range(0, len(leaves), 2)]
    return leaves[0].hex()


def signed_rows(B, run, rel):
    raw = (B / rel).read_bytes()
    rows = [json.loads(x) for x in raw.decode().splitlines()]
    ok = sha(raw) == run["rows_sha256"]
    ns = sum(ed25519_verify(run["evaluator_pubkey_ed25519"], canon({k: v for k, v in r.items() if k != "signature"}).encode(), r["signature"]) for r in rows)
    return rows, ok, ns


def T(rows):
    t = defaultdict(dict)
    for r in rows:
        t[(r["family"], r["problem"])][r["arm"]] = r
    return t


def pair(t, a, b, fams, key="discovery"):
    ks = [k for k in t if k[0] in fams and a in t[k] and b in t[k]]
    x = [bool(t[k][a][key]) for k in ks]; y = [bool(t[k][b][key]) for k in ks]
    bb = sum(p and not q for p, q in zip(x, y)); cc = sum(q and not p for p, q in zip(x, y)); n = len(ks)
    return {"n": n, "diff": (sum(x) - sum(y)) / n if n else None, "p": mcnemar(bb, cc), "prev": mcnemar(cc, bb), "b": bb, "c": cc}


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    J = lambda n: json.loads((B / n).read_text())
    man = J("MANIFEST.json"); files = man["files"]
    bad = [f for f, h in files.items() if not (B / f).is_file() or sha((B / f).read_bytes()) != h]
    check("manifest: every file present with matching SHA-256", not bad, f"{len(files)} files" + (f"; bad {bad[:3]}" if bad else ""))
    check("manifest Ed25519 signature", ed25519_verify(man["bundle_pubkey_ed25519"], canon({k: v for k, v in man.items() if k != "signature"}).encode(), man["signature"]))
    root = (B / "MERKLE_ROOT.txt").read_text().strip()
    check("Merkle root recomputed", merkle(files) == root == man["merkle_root"], root[:16])
    check("snapshot hash signed in manifest", sha((B / "e150-snapshot.json").read_bytes()) == man["snapshot_sha256"])
    pre = J("preregistration.json")
    check("preregistration hash recomputes", sha(canon({k: v for k, v in pre.items() if k != "preregistration_hash"}).encode()) == pre["preregistration_hash"])
    tl = J("timeline.json")
    check("order: preregistration < chains finished < freeze commit < confirmatory salt", tl["prereg_commit_time"] < tl["chains_finished_at"] < tl["freeze_commit_time"] < tl["confirmatory_salt_committed_at"],
          f"{tl['prereg_commit_time']} < {tl['chains_finished_at']} < {tl['freeze_commit_time']} < {tl['confirmatory_salt_committed_at']}")
    ch_raw = (B / "chains/chains.json").read_bytes(); ch = json.loads(ch_raw); fr = J("chains/freeze_record.json")
    check("chains.json matches the freeze record", sha(ch_raw) == fr["chains_sha256"])
    gh = lambda g: sha(canon(g).encode())
    hashes_ok = all(gh(g) == ch["researcher_hashes"][k] for k, g in ch["researchers"].items())
    lin_ok, detail = True, []
    for arm in ("C", "D", "B"):
        prev = ch["researchers"]["G0"]
        for gen in sorted((x for x in ch["generations"] if x["arm"] == arm), key=lambda x: x["generation"]):
            child = ch["researchers"][f"{arm}{gen['generation']}"]
            ok = gen["parent_hash"] == gh(prev) and gen["child_hash"] == gh(child) and (gen["accepted"] or gh(child) == gh(prev)) and gen["meta_used"] <= gen["meta_cap"]
            lin_ok &= ok; detail.append(f"{arm}{gen['generation']}:{'acc' if gen['accepted'] else 'kept'}")
            prev = child
    check("researcher genome hashes recompute", hashes_ok)
    check("source-level lineage: each child = accepted successor of its parent; meta budget respected", lin_ok, " ".join(detail))
    run, com = J("raw/run.json"), J("raw/salt_commitment.json")
    check("confirmatory salt commitment = SHA-256(revealed salt)", sha(bytes.fromhex(run["salt_hex_revealed_after_signing"])) == com["salt_sha256"] == run["salt_sha256"])
    check("confirmatory run bound to preregistration and frozen chains", run["preregistration_hash"] == pre["preregistration_hash"] and run["chains_sha256"] == fr["chains_sha256"])
    check("run record Ed25519 signature", ed25519_verify(run["evaluator_pubkey_ed25519"], canon({k: v for k, v in run.items() if k != "signature"}).encode(), run["signature"]))
    rows, hok, ns = signed_rows(B, run, "raw/rows.jsonl")
    check("rows hash matches signed run record", hok)
    check("every result row signed by the evaluator", ns == len(rows), f"{ns}/{len(rows)}")
    D = pre["design"]["confirmatory"]
    want = sum(n * len(D.get("arms_by_family", {}).get(f, D["arms"])) for f, n in D["families"].items())
    check("no missing or extra rows", len(rows) == want and len({(r["family"], r["problem"], r["arm"]) for r in rows}) == want, f"{len(rows)}/{want}")
    cap = pre["budgets"]["research_cap"]
    check("every research run within the research cap", all(r["research_used"] <= cap for r in rows))
    an, g, snap = J("analysis.json"), J("gates.json"), J("e150-snapshot.json")
    t = T(rows)
    h1 = pair(t, "C3", "G0", ("bool",))
    v1 = "SUPPORTED" if h1["p"] < 0.05 and h1["diff"] >= 0.05 else "CONTRADICTED" if h1["prev"] < 0.05 else "INCONCLUSIVE"
    check("H1 recomputed (exact McNemar + rate difference)", v1 == an["H1"]["verdict"] == snap["H1"]["verdict"] and h1["b"] == an["H1"]["a_only"] and h1["c"] == an["H1"]["b_only"],
          f"{v1}: diff {h1['diff']:+.4f}, C3-only {h1['b']}, G0-only {h1['c']}, p {h1['p']:.3g}")
    UNF = ("bool_F4", "thr")
    fam = {"H2": pair(t, "C3", "B3", ("bool",)), "H3a": pair(t, "C2", "C1", UNF), "H3b": pair(t, "C3", "C2", UNF), "H8": pair(t, "C3", "G0", UNF), "HR": pair(t, "C2", "X2", ("bool",))}
    ks = [k for k in t if k[0] == "bool" and "D3" in t[k] and "G0" in t[k]]
    dl = sum(t[k]["D3"]["research_used"] < t[k]["G0"]["research_used"] for k in ks); gl = sum(t[k]["D3"]["research_used"] > t[k]["G0"]["research_used"] for k in ks)
    h4d = pair(t, "D3", "G0", ("bool",))
    fam["H4"] = {"p": mcnemar(dl, gl), "noninf": h4d["diff"] >= -0.05}
    names = list(fam); adj = holm([fam[n]["p"] for n in names])
    agree = True
    for n, p in zip(names, adj):
        ok = p < 0.05 and (fam[n]["noninf"] if n == "H4" else fam[n]["diff"] is not None and fam[n]["diff"] > 0)
        v = "SUPPORTED" if ok else ("CONTRADICTED" if n != "H4" and fam[n]["prev"] < 0.05 else "NOT_SUPPORTED")
        agree &= v == an["holm_family"][n]["verdict"]
    check("Holm family verdicts recomputed (H2, H3a, H3b, H4, H8, HR)", agree, ", ".join(f"{n}={an['holm_family'][n]['verdict']}" for n in names))
    h7 = pair(t, "C3", "G0", ("bool",), key="false_promotion")
    check("H7 false-promotion safety recomputed", ("PASS" if h7["p"] >= 0.05 else "FAIL") == an["H7_false_promotion"]["verdict"])
    if (B / "raw_replication/run.json").exists():
        rr = J("raw_replication/run.json")
        check("replication salt commitment and signature", sha(bytes.fromhex(rr["salt_hex_revealed_after_signing"])) == J("raw_replication/salt_commitment.json")["salt_sha256"]
              and ed25519_verify(rr["evaluator_pubkey_ed25519"], canon({k: v for k, v in rr.items() if k != "signature"}).encode(), rr["signature"]))
        rrows, rok, rns = signed_rows(B, rr, "raw_replication/rows.jsonl")
        check("replication rows signed and hashed", rok and rns == len(rrows), f"{rns}/{len(rrows)} on {rr['host']}")
        h5 = pair(T(rrows), "C3", "G0", ("bool",))
        v5 = "SUPPORTED" if h5["p"] < 0.05 and h5["diff"] > 0 else "CONTRADICTED" if h5["prev"] < 0.05 else "NOT_SUPPORTED"
        check("H5 replication verdict recomputed", v5 == an["H5_replication"]["verdict"], v5)
    promo = "PROMOTED" if all(x["status"] in ("PASS", "NOT_APPLICABLE") for x in g["gates"].values()) else "NOT_PROMOTED"
    check("promotion follows the gate matrix", promo == g["promotion"] == snap["promotion"], promo)
    check("public snapshot cites this bundle and the fixed status", snap["merkle_root"] == root and snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    n_ok = sum(c[1] for c in CHECKS)
    print(f"\n{n_ok}/{len(CHECKS)} checks passed")
    return 0 if n_ok == len(CHECKS) else 1


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