#!/usr/bin/env python3
"""Standalone verifier for the E142 production replication bundle (stdlib + cryptography; imports no CAIN code).

  python3 -I verify_e142_replication.py <bundle_dir>

Checks: manifest hashes and Merkle root; every verdict's Ed25519 signature against the published evaluator key;
each verdict binds its experiment id, family and prereg hash; no experiment overlaps the sealed bundle; for every
test the wins/losses/ties, mean difference, one-sided sign-test p, Holm decision and verdict label are recomputed
from the raw per-instance scores; no p is displayed as 0.
"""
import hashlib
import json
import math
import sys
from pathlib import Path

D = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
OK, FAIL = [], []
PRACTICAL = 0.02
TESTS = [("OW1", "ow_explore", "frontier", "random", lambda p: True, 30),
         ("OW2", "ow_model", "full", "facts", lambda p: True, 30),
         ("OW3", "ow_transfer", "gated", "scratch", lambda p: p["budget_mult"] == 0.05, 30),
         ("OW3b", "ow_transfer", "gated", "ungated", lambda p: True, 30),
         ("OW4", "ow_goal", "full", "e141_best", lambda p: True, 30)]


def check(name, cond, detail=""):
    (OK if cond else FAIL).append(name + ("" if cond else f": {detail}"))


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


def merkle(leaves):
    if not leaves:
        return hashlib.sha256(b"").hexdigest()
    lv = [hashlib.sha256(b"\x00" + bytes.fromhex(h)).digest() for h in leaves]
    while len(lv) > 1:
        lv = [hashlib.sha256(b"\x01" + lv[i] + lv[i + 1]).digest() if i + 1 < len(lv) else lv[i] for i in range(0, len(lv), 2)]
    return lv[0].hex()


def log10_sign_p(w, l):
    n = w + l
    if n == 0:
        return 0.0
    logs = [math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1) - n * math.log(2) for i in range(w, n + 1)]
    m = max(logs)
    return (m + math.log(sum(math.exp(x - m) for x in logs))) / math.log(10)


man = json.loads((D / "MANIFEST.json").read_text())
for f, h in man["files"].items():
    check(f"hash {f}", hashlib.sha256((D / f).read_bytes()).hexdigest() == h)
check("merkle root", merkle([man["files"][f] for f in sorted(man["files"])]) == man["merkle_root"])
S = json.loads((D / "REPLICATION.json").read_text())
rows = [json.loads(l) for l in (D / "experiments.jsonl").read_text().splitlines() if l]
check("not confirmatory", S["status"]["confirmatory"] is False and S["status"]["agi"] == "NOT ESTABLISHED")
check("disjoint from sealed bundle", S["overlap_with_sealed_bundle"] == [])
check("different evaluator key than sealed run", bool(S.get("sealed_bundle_evaluator_pubkey")) and S["evaluator_pubkey"] != S["sealed_bundle_evaluator_pubkey"])

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey  # noqa: E402
pk = Ed25519PublicKey.from_public_bytes(bytes.fromhex(S["evaluator_pubkey"]))
bad = 0
for x in rows:
    v = x["verdict"]
    if not v:
        continue
    try:
        pk.verify(bytes.fromhex(v["signature"]), canon({k: v[k] for k in sorted(v) if k not in ("signature", "evaluator_pubkey")}))
        if v["experiment_id"] != x["id"] or v["family"] != x["family"] or v["prereg_hash"] != x["prereg_hash"]:
            bad += 1
    except Exception:
        bad += 1
check("all verdict signatures + bindings", bad == 0, f"{bad} bad")

lps, rec = {}, {}
for tid, fam, t, c, regime, need in TESTS:
    w = l = ties = 0
    diffs = []
    for x in rows:
        v = x["verdict"]
        if not (x["family"] == fam and x["kind"] == "primary" and x["state"] in ("VERIFIED", "PARTIAL") and v
                and "instance_scores" in v and regime(x["params"])):
            continue
        s = v["instance_scores"]
        if t not in s or c not in s:
            continue
        d = sum(s[t]) / len(s[t]) - sum(s[c]) / len(s[c])
        diffs.append(d)
        w, l, ties = w + (d > 1e-12), l + (d < -1e-12), ties + (abs(d) <= 1e-12)
    r = S["tests"][tid]
    md = sum(diffs) / len(diffs) if diffs else None
    check(f"{tid} counts", (r["n_experiments"], r["wins"], r["losses"], r["ties"]) == (len(diffs), w, l, ties),
          f"{(r['n_experiments'], r['wins'], r['losses'], r['ties'])} vs {(len(diffs), w, l, ties)}")
    check(f"{tid} mean", md is None and r["mean_diff"] is None or abs(md - r["mean_diff"]) < 1e-5)
    lp = log10_sign_p(w, l)
    check(f"{tid} sign p", abs(lp - r["log10_p"]) < 1e-3)
    check(f"{tid} p never 0", r.get("p_display") not in ("0", "0.0", 0, 0.0))
    lps[tid], rec[tid] = lp, (len(diffs) < need, md)
order = sorted(lps, key=lambda k: lps[k])
stop = False
for i, k in enumerate(order):
    sig = (not stop) and 10 ** lps[k] <= 0.05 / (len(order) - i)
    stop = stop or not sig
    under, md = rec[k]
    r = S["tests"][k]
    want = ("UNDERPOWERED" if under else ("SUPPORTED" if md >= PRACTICAL else "SUPPORTED (significant but small)") if sig and md > 0
            else "NOT SUPPORTED (treatment worse)" if md is not None and md < 0 and r["losses"] > r["wins"] else "NOT SUPPORTED")
    check(f"{k} holm", r["holm"]["holm_significant"] == bool(sig))
    check(f"{k} verdict", r["verdict"] == want, f"{r['verdict']} vs {want}")

for f in FAIL:
    print("FAIL", f)
print(f"{len(OK)}/{len(OK) + len(FAIL)} replication checks pass")
sys.exit(1 if FAIL else 0)
