#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E155 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



CAP = 1200
def U(r):
    return (r["h1_gain"] if r["submitted"] else 0.0) - 0.02 * r["research_used"] / CAP


def upper(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 _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 if abs(1 + aa / c) > 1e-300 else 1e-300; h *= d * c
    return h


def t_sf(t, df):
    x = df / (df + t * t); a, b = df / 2, 0.5
    front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1 - x))
    ib = front * _betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1 - front * _betacf(b, a, 1 - x) / b
    return ib / 2 if t > 0 else 1 - ib / 2


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 gain(r):
    return r["h1_gain"] if r["submitted"] else 0.0


def split(x, y):
    """Hidden-gain and budget parts of a paired utility difference (they sum to dU); one-sided paired t for the gain part alone."""
    n = len(x); g = [gain(a) - gain(b) for a, b in zip(x, y)]; m = sum(g) / n; sd = math.sqrt(sum((v - m) ** 2 for v in g) / (n - 1)) if n > 1 else 0
    t = m / (sd / math.sqrt(n)) if sd > 0 else (math.inf if m > 0 else -math.inf if m < 0 else 0.0)
    return {"gain_part": m, "budget_part": sum(-0.02 * (a["research_used"] - b["research_used"]) / CAP for a, b in zip(x, y)) / n,
            "p_gain": 0.0 if t == math.inf else 1.0 if t == -math.inf else 0.5 if t == 0 else t_sf(t, n - 1),
            "mean_evaluations_a": sum(a["research_used"] for a in x) / n, "mean_evaluations_b": sum(b["research_used"] for b in y) / n}


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}
    B = {(r["family"], r["problem"]): r for r in rows if r["arm"] == b and r["family"] in fams}
    k = sorted(set(A) & set(B))
    if not k:
        return None
    d = [U(A[x]) - U(B[x]) for x in k]; 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
    t = m / (sd / math.sqrt(n)) if sd > 0 else (math.inf if m > 0 else -math.inf if m < 0 else 0.0)
    p = 0.0 if t == math.inf else 1.0 if t == -math.inf else 0.5 if t == 0 else t_sf(t, n - 1)
    ao = sum(A[x]["discovery"] and not B[x]["discovery"] for x in k); bo = sum(B[x]["discovery"] and not A[x]["discovery"] for x in k)
    fa = sum(A[x]["false_promotion"] and not B[x]["false_promotion"] for x in k); fb = sum(B[x]["false_promotion"] and not A[x]["false_promotion"] for x in k)
    sb = [x for x in k if B[x]["discovery"]]; sa = [x for x in k if A[x]["discovery"]]
    return {**split([A[x] for x in k], [B[x] for x in k]), "a": a, "b": b, "families": sorted(fams), "n": n, "mean_dU": round(m, 6), "sd_dU": round(sd, 6), "t": round(t, 4) if math.isfinite(t) else str(t), "p_dense": p,
            "discoveries_a": len(sa), "discoveries_b": len(sb), "a_only": ao, "b_only": bo, "p_disc": upper(ao, bo),
            "false_promotions_a": sum(A[x]["false_promotion"] for x in k), "false_promotions_b": sum(B[x]["false_promotion"] for x in k), "p_fp_worse": upper(fa, fb),
            "research_a": sum(A[x]["research_used"] for x in k), "research_b": sum(B[x]["research_used"] for x in k),
            "retention": round(sum(A[x]["discovery"] for x in sb) / len(sb), 4) if sb else None, "lost": sum(1 for x in sb if not A[x]["discovery"]), "gained": sum(1 for x in sa if not B[x]["discovery"])}




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


def chain_ok(es, msg_hash_key="hash"):
    prev = "0" * 64
    for e in es:
        if e["prev"] != prev or not ed25519_verify(e["pub"], bytes.fromhex(e["hash"]), e["sig"]):
            return False
        prev = e["hash"]
    return True


def same_rows(rows, a, b):
    """Two arms produced identical outcomes on every shared problem (same researcher in effect)."""
    key = lambda r: (r["outcome"], r["research_used"], r["submitted"], r["h1_gain"])
    A = {(r["family"], r["problem"]): key(r) for r in rows if r["arm"] == a}; B = {(r["family"], r["problem"]): key(r) for r in rows if r["arm"] == b}
    k = set(A) & set(B)
    return bool(k) and all(A[x] == B[x] for x in k)


def same_researcher(arms, rows, a, b):
    """Same source and genome, and either the same operator library or identical outcomes (an empty, unused library has a hash too)."""
    x, y = arms.get(a), arms.get(b)
    if not x or not y or x["source_sha256"] != y["source_sha256"] or x["genome"] != y["genome"]:
        return False
    return x.get("library_sha256") == y.get("library_sha256") or same_rows(rows, a, b)


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("E155_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"])
    check("arm set (sources + library versions) frozen before the salt", 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 authorized by MCPGate", 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"]; st0 = J("development/state.json")["arms"]
    def pick(x, y):
        key = lambda c: (sum(bool(d.get("accepted")) for d in st0[c]["lineage"]), sum((d.get("selection") or {}).get("mean_dU") or 0 for d in st0[c]["lineage"] if d.get("accepted")), c == x)
        return max((x, y), key=key) + "_final"
    sysarm = {"bool": pick("Cb1", "Cb2"), "opt": pick("Co1", "Co2")}
    check("colony system re-chosen from development data only", sysarm == an["colony_system"], str(sysarm))
    am = J("E155_AMENDMENT_1.json")
    check("amendment hash recomputes, amends this preregistration, predates the sealed salt", sha(canon({k: v for k, v in am.items() if k != "amendment_hash"}).encode()) == am["amendment_hash"] == an["amendment_hash"] and am["amends_preregistration_hash"] == pre["preregistration_hash"] and am["made_at"] < cc["committed_at"])
    won = won_o = True; Q = ("gain_part", "budget_part", "p_gain", "mean_evaluations_a", "mean_evaluations_b", "p_dense", "mean_dU", "discoveries_a", "discoveries_b", "false_promotions_a", "false_promotions_b")
    near = lambda p, h: all(abs(p[q] - h[q]) < 1e-9 for q in Q) and abs(p["gain_part"] + p["budget_part"] - p["mean_dU"]) < 2e-6
    for name, dom, b in (("S1_bool_vs_GEN", "bool", "GEN_final"), ("S1_bool_vs_Sb", "bool", "Sb_final"), ("S1_opt_vs_GEN", "opt", "GEN_final"), ("S1_opt_vs_So", "opt", "So_final")):
        h, a = Hh[name], sysarm[dom]
        if same_researcher(arms, rows["confirmation"], a, b):
            won = won_o = False; check(f"{name} NOT_TESTABLE (identical researchers)", h["original_rule"] == h["amended_rule"] == "NOT_TESTABLE"); continue
        p = pair(rows["confirmation"], a, b, {dom}); o = p["mean_dU"] > 0 and p["p_dense"] <= 0.0125; m = o and p["gain_part"] > 0 and p["p_gain"] <= 0.0125 and p["discoveries_a"] >= p["discoveries_b"]
        check(f"{name} recomputed under both rules", near(p, h) and (h["original_rule"] == "SUPPORTED") == o and (h["amended_rule"] == "SUPPORTED") == m and (h.get("budget_label") == "BUDGET-DRIVEN PASS") == (o and not m), f"original {h['original_rule']}, amended {h['amended_rule']}; gain {p['gain_part']:+.5f} budget {p['budget_part']:+.5f}")
        if o:
            r = pair(rows["replication"], a, b, {dom}); ro = r["mean_dU"] > 0 and r["p_dense"] < 0.05; rm = ro and r["gain_part"] > 0 and r["p_gain"] < 0.05 and r["discoveries_a"] >= r["discoveries_b"]; R_ = h["replication"]
            check(f"{name} replication recomputed under both rules", near(r, R_) and (R_["original_rule"] == "SUPPORTED") == ro and (R_["amended_rule"] == "SUPPORTED") == rm); won &= m and rm; won_o &= ro
        else:
            won = won_o = False
    for name, h in Hh.items():
        if name.startswith("T1_") and "p_dense" in h:
            p = pair(rows["confirmation"], h["a"], h["b"], set(h["families"])); check(f"{name} recomputed", abs(p["p_dense"] - h["p_dense"]) < 1e-9 and abs(p["mean_dU"] - h["mean_dU"]) < 1e-9)
    check("NAME_RULE outcome follows from the recomputed contrasts", an["name_rule_outcome"] == ("superorganism (candidate)" if won else "AGI-RSI research organism") and an["superorganism_supported"] == won and an["name_rule_outcome_original"] == ("superorganism (candidate)" if won_o else "AGI-RSI research organism"), an["name_rule_outcome"] + " (amended) / " + an["name_rule_outcome_original"] + " (original)")
    D = pre["confirmation"]; n_arms = len(arms)
    for tag, spec in (("confirmation", D["populations"]), ("replication", D["replication"])):
        got = [(r["arm"], r["family"], r["problem"]) for r in rows[tag]]; want = {(x, f, i) for x in arms for f, n in spec.items() for i in range(n)}
        check(f"{tag} design complete: every arm x problem exactly once", len(got) == len(set(got)) and set(got) == want, f"{len(got)} rows")
    snap = J("e155-snapshot.json")
    check("snapshot cites this preregistration, NAME_RULE outcome and status", snap["preregistration_hash"] == pre["preregistration_hash"] and snap["name_rule"] == pre["NAME_RULE"] and snap["name_rule_outcome"] == an["name_rule_outcome"] and snap["name_rule_outcome_original"] == an["name_rule_outcome_original"]
          and {k: x["verdict"] for k, x in snap["hypotheses"].items()} == {k: x["verdict"] for k, x in Hh.items()} and snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"})
    st = J("development/state.json"); ok = True
    for arm, A_ in st["arms"].items():
        prev = None
        for d in A_["lineage"]:
            ok &= prev is None or d["parent_sha256"] == prev; prev = d["child_sha256"] if d.get("accepted") else d["parent_sha256"]
    check("lineage: every generation starts from its actual parent; rejected generations keep the parent", ok)
    check("self-improvement memory chains linked and signed", all(chain_ok(es) for es in J("development/memory_chains.json").values()))
    lib = J("development/library_public.json")
    check("operator library chains linked and signed (code withheld)", all(chain_ok(es) for es in lib.values()) and not any("source" in e for es in lib.values() for e in es), f"{sum(len(v) for v in lib.values())} modules")
    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")
    check("no research-procedure or library source in the public bundle", not any(p.suffix == ".py" and p.name not in ("verify_e155_offline.py", "verify_tamper_e155.py") for p in B.rglob("*.py"))
          and all(not c.get("source_published") for c in L(B / "development/candidates_public.jsonl")))
    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()
