#!/usr/bin/env python3
"""Standalone offline verifier for the CAIN-42 E148 Confirmatory RSI Evidence Bundle.
Imports ZERO CAIN code (Python stdlib + `cryptography` only).

  python3 -I verify_e148_offline.py <bundle_dir>

Checks:
  1. Manifest Ed25519 signature, every file SHA-256 hash, and RFC-style binary Merkle root.
  2. Preregistration SHA-256 hash and frozen parent/candidate/source immutability hashes.
  3. Equal-compute invariant (parent n_cand == candidate n_cand == 32).
  4. Ed25519 signatures on every raw confirmatory block, held-out block, replication block, and governance receipt.
  5. Full statistical recomputation from raw experimental rows: primary means, paired differences,
     wins/losses/ties, exact one-sided sign-test p, paired Student-t p, 95% CI, and H1 verdict.
  6. Held-out unfamiliar-domain statistical recomputation and non-inferiority verdict.
  7. Fresh-seed replication statistical recomputation and pass verdict.
  8. Strict non-zero p-value check (no p == 0.0 reported) and mandatory status labels.

Note: Passing this integrity & recomputation verifier confirms mathematical consistency and bundle
tamper-evidence; it does NOT by itself establish independent third-party reproduction.
"""
from __future__ import annotations

import hashlib
import json
import math
import sys
from pathlib import Path

ALPHA = 0.05


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


def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def verify_ed25519(pub_hex: str, sig_hex: str, msg: bytes) -> bool:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_hex)).verify(bytes.fromhex(sig_hex), msg)
        return True
    except Exception:
        return False


def merkle(leaves: list[str]) -> str:
    if not leaves:
        return sha(b"")
    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 exact_sign_p(w: int, l: int) -> float:
    n = w + l
    if n == 0:
        return 1.0
    logs = [math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1) - n * math.log(2.0) for i in range(w, n + 1)]
    m = max(logs)
    return min(1.0, math.exp(m) * sum(math.exp(x - m) for x in logs))


def _betacf(a: float, b: float, x: float) -> float:
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c, d = 1.0, 1.0 - qab * x / qap
    d = 1.0 / (d if abs(d) > 1e-300 else 1e-300)
    h = d
    for m in range(1, 301):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d; d = 1e-300 if abs(d) < 1e-300 else d
        c = 1.0 + aa / c; c = 1e-300 if abs(c) < 1e-300 else c
        d = 1.0 / d; h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d; d = 1e-300 if abs(d) < 1e-300 else d
        c = 1.0 + aa / c; c = 1e-300 if abs(c) < 1e-300 else c
        d = 1.0 / d; de = d * c; h *= de
        if abs(de - 1.0) < 3e-16:
            break
    return h


def betainc(a: float, b: float, x: float) -> float:
    if x <= 0:
        return 0.0
    if x >= 1:
        return 1.0
    lb = math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x)
    if x < (a + 1.0) / (a + b + 2.0):
        return math.exp(lb) * _betacf(a, b, x) / a
    return 1.0 - math.exp(lb) * _betacf(b, a, 1.0 - x) / b


def t_sf(t: float, df: int) -> float:
    tail = 0.5 * betainc(df / 2.0, 0.5, df / (df + t * t))
    return tail if t > 0 else 1.0 - tail


def paired_t(diffs: list[float]) -> dict:
    n = len(diffs)
    m = sum(diffs) / n if n else 0.0
    if n < 2:
        return {"n": n, "mean": m, "t": None, "df": n - 1, "p_one_sided": 1.0}
    sd = math.sqrt(sum((d - m) ** 2 for d in diffs) / (n - 1))
    if sd == 0:
        return {"n": n, "mean": round(m, 9), "t": None, "df": n - 1, "p_one_sided": 1e-300 if m > 0 else 1.0}
    t = m / (sd / math.sqrt(n))
    return {"n": n, "mean": round(m, 9), "t": round(t, 6), "df": n - 1, "p_one_sided": max(1e-300, t_sf(t, n - 1))}


def check_sig(obj: dict, pub: str) -> bool:
    sig = obj.get("signature")
    if not sig:
        return False
    body = {k: obj[k] for k in sorted(obj) if k != "signature"}
    return verify_ed25519(pub, sig, canon(body).encode())


def main(bundle_dir: Path) -> int:
    d = Path(bundle_dir)
    checks: list[tuple[str, bool, str]] = []

    def ck(name: str, ok: bool, info: str = "") -> None:
        checks.append((name, bool(ok), info))
        print(("PASS " if ok else "FAIL ") + name + (f"  [{info}]" if info else ""))

    man_path = d / "MANIFEST.json" if (d / "MANIFEST.json").exists() else d / "manifest.json"
    man = json.loads(man_path.read_text())
    pub = man["evidence_pubkey"]
    ck("manifest Ed25519 signature", check_sig(man, pub))

    bad_files = [f for f, h in man["files"].items() if not (d / f).exists() or sha((d / f).read_bytes()) != h]
    ck("manifest file SHA-256 hashes", not bad_files, f"{len(man['files'])} files, {len(bad_files)} mismatched")

    calc_merkle = merkle([man["files"][f] for f in sorted(man["files"])])
    ck("Merkle root recomputed", calc_merkle == man["merkle_root"], calc_merkle[:16])

    prereg = json.loads((d / "preregistration.json").read_text())
    prereg_recomp = sha(canon({k: v for k, v in prereg.items() if k != "preregistration_hash"}).encode())
    ck("preregistration SHA-256 hash", prereg_recomp == prereg["preregistration_hash"], prereg_recomp[:16])

    p_hash = sha((d / "parent/g147_parent.json").read_bytes())
    c_hash = sha((d / "candidate/g148_candidate.json").read_bytes())
    a_hash = sha((d / "candidate/agent_e148.py").read_bytes())
    ck("frozen parent & candidate immutability",
       p_hash == prereg["parent"]["config_sha256"] and c_hash == prereg["candidate"]["config_sha256"] and a_hash == prereg["candidate"]["agent_sha256"])

    p_cfg = json.loads((d / "parent/g147_parent.json").read_text())
    c_cfg = json.loads((d / "candidate/g148_candidate.json").read_text())
    ck("equal compute verified (n_cand == 32)", p_cfg["n_cand"] == 32 and c_cfg["n_cand"] == 32, f"parent={p_cfg['n_cand']}, cand={c_cfg['n_cand']}")

    # Primary blocks & signatures & recomputation
    raw_p = json.loads((d / "raw_results/primary_blocks.json").read_text())
    p_blocks = raw_p["blocks"]
    ck("confirmatory block Ed25519 signatures", all(check_sig(b, pub) for b in p_blocks), f"{len(p_blocks)} blocks")
    ck("confirmatory block count matches preregistration", len(p_blocks) == prereg["experimental_design"]["confirmatory_blocks_K"], f"{len(p_blocks)}")
    ck("no duplicate primary blocks", len({b["block"] for b in p_blocks}) == len(p_blocks))

    paired = json.loads((d / "paired_comparisons/primary_results.json").read_text())
    ps = paired["primary_g148_vs_g147"]
    t_vals = [b["arms"]["g148_candidate"]["verified_discoveries"] for b in p_blocks]
    c_vals = [b["arms"]["g147_parent"]["verified_discoveries"] for b in p_blocks]
    diffs = [a - b for a, b in zip(t_vals, c_vals)]
    w = sum(x > 1e-12 for x in diffs)
    l = sum(x < -1e-12 for x in diffs)
    mean_d = sum(diffs) / len(diffs)
    p_sign = exact_sign_p(w, l)
    pt = paired_t(diffs)
    ck("primary paired means & wins/losses recomputed",
       abs(mean_d - ps["mean_diff"]) < 1e-5 and (w, l) == (ps["wins"], ps["losses"]),
       f"mean={mean_d:+.4f}/40, W/L={w}/{l}")
    ck("primary exact sign-test & paired t-test recomputed",
       abs(p_sign - ps["exact_sign_p_one_sided"]) < 1e-9 and abs(pt["p_one_sided"] - ps["paired_t"]["p_one_sided"]) < 1e-6,
       f"sign_p={p_sign:.4g}, t_p={pt['p_one_sided']:.4g}")

    want_h1 = "SUPPORTED" if (mean_d > 0 and ps["ci95_t"][0] > 0 and p_sign < ALPHA and ps["paired_permutation_p_one_sided"] < ALPHA and pt["p_one_sided"] < ALPHA) else (
        "CONTRADICTED" if (mean_d < 0 and ps["ci95_t"][1] < 0) else "INCONCLUSIVE"
    )
    ck("primary H1 verdict matches recomputed criteria", paired["H1_verdict"] == want_h1, want_h1)

    # Held-out blocks
    raw_u = json.loads((d / "raw_results/heldout_blocks.json").read_text())
    u_blocks = raw_u["blocks"]
    ck("held-out block Ed25519 signatures", all(check_sig(b, pub) for b in u_blocks), f"{len(u_blocks)} blocks")
    ho = json.loads((d / "held_out/unfamiliar_results.json").read_text())
    ud = [b["arms"]["g148_candidate"]["verified_discoveries"] - b["arms"]["g147_parent"]["verified_discoveries"] for b in u_blocks]
    um = sum(ud) / len(ud)
    ck("held-out unfamiliar mean recomputed", abs(um - ho["stats"]["mean_diff"]) < 1e-5, f"mean={um:+.4f}/40 ({um/40*100:+.2f}pp)")

    # Replication
    rep = json.loads((d / "replications/fresh_seed_replication.json").read_text())
    ck("replication block Ed25519 signatures", all(check_sig(b, pub) for b in rep["blocks"]), f"{len(rep['blocks'])} blocks")
    rd = [b["arms"]["g148_candidate"]["verified_discoveries"] - b["arms"]["g147_parent"]["verified_discoveries"] for b in rep["blocks"]]
    rm = sum(rd) / len(rd)
    rw, rl = sum(x > 1e-12 for x in rd), sum(x < -1e-12 for x in rd)
    rp_sign = exact_sign_p(rw, rl)
    ck("replication stats recomputed",
       abs(rm - rep["summary"]["mean_diff"]) < 1e-5 and abs(rp_sign - rep["summary"]["exact_sign_p_one_sided"]) < 1e-9,
       f"mean={rm:+.4f}/40, W/L={rw}/{rl}, sign_p={rp_sign:.4g}")

    # Governance receipt
    gov = json.loads((d / "verification/mcpgate_governance.json").read_text())
    ck("governance receipt Ed25519 signature", check_sig(gov, pub))

    # No p == 0 anywhere
    all_ps = [
        ps["exact_sign_p_one_sided"], ps["paired_permutation_p_one_sided"], ps["paired_t"]["p_one_sided"],
        ho["stats"]["exact_sign_p_one_sided"], ho["stats"]["paired_permutation_p_one_sided"],
        rep["summary"]["exact_sign_p_one_sided"], rep["summary"]["paired_permutation_p_one_sided"],
    ]
    ck("no p == 0 reported", all(p > 0.0 for p in all_ps), f"min_p={min(all_ps):.4g}")

    # Canonical snapshot parity & mandatory status labels
    snap = json.loads((d / "public_snapshots/e148-snapshot.json").read_text())
    ck("status labels fixed (AGI NOT ESTABLISHED, RSI EXPERIMENTAL)",
       snap["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"} and snap["entity"] == "FIRME AI CORPORATION")
    ck("snapshot matches recomputed H1 & primary counts",
       snap["primary"]["H1_verdict"] == want_h1 and abs(snap["primary"]["mean_diff"] - mean_d) < 1e-5 and snap["primary"]["n_blocks"] == len(p_blocks))

    passed = sum(1 for _, ok, _ in checks if ok)
    print(f"\n{passed}/{len(checks)} checks passed")
    return 0 if passed == len(checks) else 1


if __name__ == "__main__":
    raise SystemExit(main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1]))
