#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E151 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.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 L(p):
    return [json.loads(x) for x in p.read_text().splitlines() if x.strip()]


def pair(rows, a, b, fams):
    A = {(r["family"], r["problem"]): r for r in rows if r["arm"] == a and r["family"] in fams}
    Bm = {(r["family"], r["problem"]): r for r in rows if r["arm"] == b and r["family"] in fams}
    k = sorted(set(A) & set(Bm))
    if not k:
        return None
    ao = sum(A[x]["discovery"] and not Bm[x]["discovery"] for x in k); bo = sum(Bm[x]["discovery"] and not A[x]["discovery"] for x in k)
    less = sum(A[x]["research_used"] < Bm[x]["research_used"] for x in k); more = sum(A[x]["research_used"] > Bm[x]["research_used"] for x in k)
    return {"n": len(k), "a_only": ao, "b_only": bo, "rate_diff": round((sum(A[x]["discovery"] for x in k) - sum(Bm[x]["discovery"] for x in k)) / len(k), 5),
            "p_a_better": mcnemar(ao, bo), "p_a_cheaper": mcnemar(less, more)}


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("manifest file hashes match disk", 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)))
    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"], canon({k: v for k, v in man.items() if k != "signature"}).encode(), man["signature"]))
    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"])
    cc, rc = J("confirm/confirmation_salt_commitment.json"), J("confirm/replication_salt_commitment.json")
    check("preregistered before the confirmation salt existed", pre["preregistered_at"] < cc["committed_at"], f"{pre['preregistered_at']} < {cc['committed_at']}")
    check("arm set frozen before the salt (hash in the commitment)", sha((B / "confirm/arms.json").read_bytes()) == cc["arms_frozen_sha256"] == rc["arms_frozen_sha256"])
    rows = {}
    for tag, com in (("confirmation", cc), ("replication", rc)):
        run = J(f"confirm/{tag}_run.json"); raw = (B / f"confirm/{tag}_rows.jsonl").read_bytes(); rr = [json.loads(x) for x in raw.decode().splitlines()]
        good = 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 rr)
        check(f"{tag} rows bound to run and all signed", sha(raw) == run["rows_sha256"] and good == len(rr) == run["n_rows"], f"{good}/{len(rr)}")
        check(f"{tag} salt revealed matches its prior commitment", sha(bytes.fromhex(run["salt_hex_revealed_after_signing"])) == com["salt_sha256"])
        check(f"{tag}: every run went through MCPGate (ALLOW)", all(r.get("mcpgate_decision") == "ALLOW" for r in rr if "copied_from" not in r))
        rows[tag] = rr
    an = J("analysis.json"); Hh = an["hypotheses"]; arms = J("confirm/arms.json")["arms"]
    ident = {k for k, v in arms.items() if v.get("identical_to") == "A"}
    for name, a, b, fams, tag in (("H1", "D_final", "A", {"bool"}, "confirmation"), ("H2", "E_final", "D_final", {"bool"}, "confirmation"),
                                  ("H5", "D_final", "A", {"bool"}, "replication"), ("H6", "D_final", "A", {"thr", "bool_F4"}, "confirmation"),
                                  ("H12", "E_final", "A", {"thr", "bool_F4"}, "confirmation")):
        h = Hh[name]
        if h["verdict"] == "NOT_TESTABLE":
            same = arms[a]["source_sha256"] == arms[b]["source_sha256"] and arms[a]["genome"] == arms[b]["genome"]
            check(f"{name} NOT_TESTABLE because the researchers are identical", same or (a in ident and b in ident) or (a in ident and b == "A"))
            continue
        p = pair(rows[tag], a, b, fams)
        check(f"{name} recomputed from signed rows", p["a_only"] == h["a_only"] and p["b_only"] == h["b_only"] and abs(p["p_a_better"] - h["p_a_better"]) < 1e-12, f"{h['verdict']} {p['a_only']}/{p['b_only']} p={p['p_a_better']:.4g}")
    snap = J("e151-snapshot.json")
    check("public snapshot cites this preregistration, promotion and status", snap["preregistration_hash"] == pre["preregistration_hash"] and snap["promotion"] == an["promotion"]
          and snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    st = J("development/state.json"); ok = True
    for arm in ("D", "E"):
        prev = None
        for d in st["arms"][arm]["lineage"]:
            ok &= prev is None or d["parent_sha256"] == prev
            prev = d["child_sha256"] if d.get("accepted") else d["parent_sha256"]
    check("lineage: each generation starts from its actual parent; rejected generations keep the parent", ok)
    mem = J("development/memory_chains.json"); okm, n = True, 0
    for arm, es in mem.items():
        prev = "0" * 64
        for e in es:
            n += 1; okm &= e["prev"] == prev and ed25519_verify(e["pub"], bytes.fromhex(e["hash"]), e["sig"]); prev = e["hash"]
    check("self-improvement memory chains linked and signed", okm, f"{n} entries")
    led = L(B / "development/api_ledger.jsonl"); usd = sum((x.get("usage") or {}).get("cost_usd_estimate", 0) or 0 for x in led)
    check("model spend within the preregistered cap", usd <= pre["model"]["budget_usd_cap"], f"${usd:.4f} over {len(led)} calls")
    cands = L(B / "development/candidates_public.jsonl")
    check("no research-procedure source in the public bundle", all(not c.get("source_published") for c in cands) and not any(p.suffix == ".py" and p.name not in ("verify_e151_offline.py", "verify_tamper_e151.py") for p in B.rglob("*.py")))
    passed = sum(1 for _, o in CHECKS if o)
    print(f"\n{passed}/{len(CHECKS)} checks passed")
    sys.exit(0 if passed == len(CHECKS) else 1)


if __name__ == "__main__":
    main()
