#!/usr/bin/env python3
"""E408-R standalone offline verifier (ZERO CAIN imports).

Independently verifies:
  1. Zero leaked engine source files in the evidence bundle
  2. SHA-256 of every file, binary Merkle root, canonical signed body, and Ed25519 signature
  3. Preregistration SHA-256 freeze and blind salt commitments
  4. Every Ed25519 signature, SHA-256 hash-chain link, nonce uniqueness, and authority-firewall
     flag across all exported governed shared-memory chains
  5. Complete independent re-execution of every promoted champion AST across all 48 worlds
     (5,760 sealed events x 5 arms = 28,800 AST evaluations) directly from the revealed salts
  6. Exact recomputation of all paired sign-test p-values, H1-H7 hypothesis verdicts, headline,
     acceptance registry, final report, public summary, and zero-model-call attestation.

Usage: python3 -I verify_e408r_offline.py <bundle_dir>
"""
from __future__ import annotations

import hashlib
import json
import math
import random
import sys
from pathlib import Path
from typing import Any

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

EX = {
    "E408-R_MANIFEST.json",
    "E408-R_SIGNED_BODY.json",
    "E408-R_VERIFICATION_RESULTS.json",
    "MANIFEST.json",
    "MERKLE_ROOT.txt",
    "PUBLICATION.json",
    "E408-R_OMEGA_SEAL.json",
    "E408-R_TAMPER_RESULTS.json",
}
ATTRS = ("op", "risk", "depth", "signed", "tenant_ok", "quota", "anomaly", "lineage")
DOMAINS = {
    "op": (0, 1, 2, 3),
    "risk": (0, 1, 2, 3, 4),
    "depth": (0, 1, 2, 3, 4),
    "signed": (0, 1),
    "tenant_ok": (0, 1),
    "quota": (0, 1, 2, 3, 4),
    "anomaly": (0, 1, 2, 3),
    "lineage": (0, 1),
}
MAX_CLAUSES = 6
WORLDS_PER_SALT = 24
GENS = 4


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


def canon(o: Any) -> bytes:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def merkle(paths: list[Path]) -> str:
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode("ascii")) for i in range(0, len(leaves), 2)]
    return leaves[0] if leaves else sha(b"")


def rng_for(*parts: Any) -> random.Random:
    seed = int(hashlib.sha256("|".join(str(p) for p in parts).encode("utf-8")).hexdigest()[:16], 16)
    return random.Random(seed)


def eval_lit(lit: list[Any], ev: dict[str, int]) -> bool:
    a, op, val = lit[0], lit[1], int(lit[2])
    v = int(ev[a])
    return v == val if op == "==" else (v >= val if op == ">=" else v <= val)


def eval_clause(cl: list[list[Any]], ev: dict[str, int]) -> bool:
    return bool(cl) and all(eval_lit(lit, ev) for lit in cl)


def eval_prog(prog: list[list[list[Any]]], ev: dict[str, int]) -> int:
    for cl in prog[:MAX_CLAUSES]:
        if eval_clause(cl, ev):
            return 1
    return 0


def canonical_clause(cl: list[list[Any]]) -> list[list[Any]]:
    return sorted([[str(a), str(o), int(v)] for a, o, v in cl], key=lambda x: (x[0], x[1], x[2]))


def _rand_ev(r: random.Random) -> dict[str, int]:
    return {a: r.choice(DOMAINS[a]) for a in ATTRS}


def _force_lit(ev: dict[str, int], lit: list[Any], satisfy: bool, r: random.Random) -> None:
    a, op, val = lit[0], lit[1], int(lit[2])
    dom = DOMAINS[a]
    if satisfy:
        ch = [v for v in dom if (v == val if op == "==" else (v >= val if op == ">=" else v <= val))]
    else:
        ch = [v for v in dom if not (v == val if op == "==" else (v >= val if op == ">=" else v <= val))]
    ev[a] = r.choice(ch)


def _sample_match(cl, all_cl, r, exclusive_idx=None):
    for _ in range(200):
        ev = _rand_ev(r)
        for lit in cl:
            _force_lit(ev, lit, True, r)
        if exclusive_idx is not None and any(eval_clause(c, ev) for i, c in enumerate(all_cl) if i != exclusive_idx):
            continue
        if eval_clause(cl, ev):
            return ev
    ev = _rand_ev(r)
    for lit in cl:
        _force_lit(ev, lit, True, r)
    return ev


def _sample_nm(cl, all_cl, drop_idx, r):
    for _ in range(300):
        ev = _rand_ev(r)
        for i, lit in enumerate(cl):
            _force_lit(ev, lit, i != drop_idx, r)
        if eval_prog(all_cl, ev) == 0:
            return ev
    ev = {"op": 0, "risk": 0, "depth": 0, "signed": 1, "tenant_ok": 1, "quota": 0, "anomaly": 0, "lineage": 1}
    for i, lit in enumerate(cl):
        _force_lit(ev, lit, i != drop_idx, r)
    return ev


def _sample_clean(all_cl, r):
    for _ in range(200):
        ev = _rand_ev(r)
        if eval_prog(all_cl, ev) == 0:
            return ev
    return {"op": 0, "risk": 0, "depth": 0, "signed": 1, "tenant_ok": 1, "quota": 0, "anomaly": 0, "lineage": 1}


def regen_sealed_events(salt: str, world_idx: int) -> list[dict[str, Any]]:
    """Independently regenerate exact sealed held-out events from salt + world_idx."""
    r = rng_for("e408r-gt", salt, world_idx)
    r0 = r.choice([2, 3])
    d0 = r.choice([1, 2])
    c0_guard = r.choice([["risk", ">=", r0], ["depth", ">=", d0]])
    c0 = canonical_clause([["signed", "==", 0], ["tenant_ok", "==", 0], c0_guard])
    q1 = r.choice([2, 3])
    c1_guard = r.choice([["risk", ">=", r.choice([2, 3])], ["lineage", "==", 0]])
    c1 = canonical_clause([["op", "==", 2], ["quota", ">=", q1], c1_guard])
    a2 = r.choice([2, 3])
    c2_guard = r.choice([["lineage", "==", 0], ["depth", ">=", r.choice([2, 3])]])
    c2 = canonical_clause([["op", "==", 3], ["anomaly", ">=", a2], c2_guard])
    d3 = r.choice([3, 4])
    r3 = r.choice([3, 4])
    c3_guard = r.choice([["quota", ">=", r.choice([2, 3])], ["anomaly", ">=", r.choice([1, 2])]])
    c3 = canonical_clause([["depth", ">=", d3], ["risk", ">=", r3], c3_guard])
    gt = [c0, c1, c2, c3]

    core_attrs = [{"signed", "tenant_ok"}, {"op", "quota"}, {"op", "anomaly"}, {"depth", "risk"}]
    guard_indices = [next(i for i, lit in enumerate(cl) if lit[0] not in core_attrs[k]) for k, cl in enumerate(gt)]

    rs = rng_for("e408r-sealed", salt, world_idx)
    sealed = []
    for k in range(4):
        for _ in range(15):
            sealed.append({"x": _sample_match(gt[k], gt, rs, exclusive_idx=k), "y": 1})
        for _ in range(10):
            sealed.append({"x": _sample_nm(gt[k], gt, guard_indices[k], rs), "y": 0})
    for _ in range(20):
        sealed.append({"x": _sample_clean(gt, rs), "y": 0})
    rs.shuffle(sealed)
    return sealed


def sign_test_p(w: int, l: int) -> float:
    n = w + l
    if n == 0:
        return 1.0
    k = min(w, l)
    return min(1.0, 2.0 * sum(math.comb(n, i) for i in range(k + 1)) / (2 ** n))


def main() -> int:
    if len(sys.argv) < 2:
        print("usage: verify_e408r_offline.py <bundle_dir>")
        return 2
    B = Path(sys.argv[1]).resolve()
    checks: list[tuple[str, bool, str]] = []

    def chk(name: str, ok: bool, detail: str = "") -> None:
        checks.append((name, bool(ok), detail))

    # 1. No leaked engine source
    py_files = sorted(str(p.relative_to(B)) for p in B.rglob("*.py") if "__pycache__" not in p.parts)
    chk("no_engine_source_leak", py_files == ["verify_e408r_offline.py"], f"py={py_files}")

    # 2. Manifest, Merkle root, Ed25519 signature
    man = json.loads((B / "E408-R_MANIFEST.json").read_text())
    man2 = json.loads((B / "MANIFEST.json").read_text())
    chk("manifest_mirror_match", man == man2, "MANIFEST.json matches E408-R_MANIFEST.json")

    actual_files = sorted(
        p for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in EX and "__pycache__" not in p.parts
    )
    actual_map = {str(p.relative_to(B)): sha(p.read_bytes()) for p in actual_files}
    chk("file_hashes_match", man.get("files") == actual_map, f"files={len(actual_map)}")

    mk = merkle(actual_files)
    mk_txt = (B / "MERKLE_ROOT.txt").read_text().strip()
    chk("merkle_root_match", man.get("merkle_root") == mk == mk_txt, mk[:16])

    sig_hex = man.get("signature", "")
    body_dict = {k: v for k, v in man.items() if k != "signature"}
    signed_body = (B / "E408-R_SIGNED_BODY.json").read_bytes()
    chk("signed_body_canonical", signed_body == canon(body_dict), "canonical JSON match")

    sig_ok = False
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(sig_hex), signed_body
        )
        sig_ok = True
    except (ValueError, InvalidSignature, KeyError):
        sig_ok = False
    chk("manifest_signature_valid", sig_ok, f"pub={str(man.get('pubkey_ed25519',''))[:16]}")

    # 3. Preregistration freeze & salt commitments
    pre_bytes = (B / "E408-R_PREREGISTRATION.json").read_bytes()
    pre = json.loads(pre_bytes)
    frz = json.loads((B / "E408-R_PREREGISTRATION_FREEZE.json").read_text())
    chk("prereg_freeze_hash", frz.get("preregistration_sha256") == sha(pre_bytes), frz.get("preregistration_sha256", "")[:16])

    salt_rev = json.loads((B / "E408-R_SALT_REVEALED.json").read_text())
    salts = salt_rev.get("salts", {})
    salt_commit_ok = (
        set(salts.keys()) == {"primary", "replication"}
        and all(
            sha(bytes.fromhex(salts[k])) == pre["salt_commitment_sha256"].get(k) == salt_rev["commitments_sha256"].get(k)
            for k in ("primary", "replication")
        )
    )
    chk("salt_commitments_match", salt_commit_ok, "primary+replication")

    # 4. Verify every exported governed memory chain (Ed25519 sigs + SHA-256 chain + nonce uniqueness + authority flag)
    cp_dir = B / "checkpoints"
    pub_files = sorted(cp_dir.glob("pubs_*.json"))
    chk("exported_chains_present", len(pub_files) >= 4, f"chains={len(pub_files)}")
    chains_ok = True
    total_chain_rows = 0
    for pf in pub_files:
        meta = json.loads(pf.read_text())
        cf = cp_dir / pf.name.replace("pubs_", "chain_").replace(".json", ".jsonl")
        if not cf.exists():
            chains_ok = False
            break
        lines = [json.loads(l) for l in cf.read_text().splitlines() if l.strip()]
        prev = "0" * 64
        nonces: set[str] = set()
        for idx, row in enumerate(lines, 1):
            total_chain_rows += 1
            if (
                row.get("seq") != idx
                or row.get("tenant") != meta["tenant"]
                or row.get("prev_hash") != prev
                or row.get("nonce") in nonces
                or row.get("grants_authority") is not False
                or row.get("executable") is not False
                or row.get("authority_effect") != "none"
            ):
                chains_ok = False
                break
            nonces.add(row["nonce"])
            body = {
                "schema": row["schema"],
                "tenant": row["tenant"],
                "seq": row["seq"],
                "agent": row["agent"],
                "kind": row["kind"],
                "payload": row["payload"],
                "uncertainty": round(float(row["uncertainty"]), 6),
                "verification": row["verification"],
                "nonce": row["nonce"],
                "prev_hash": row["prev_hash"],
                "created_at": row["created_at"],
            }
            bbytes = canon(body)
            sbytes = bytes.fromhex(row["sig"])
            if sha(bbytes + sbytes) != row["entry_hash"]:
                chains_ok = False
                break
            pub_h = meta["pubs"].get(row["agent"])
            if not pub_h:
                chains_ok = False
                break
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_h)).verify(sbytes, bbytes)
            except InvalidSignature:
                chains_ok = False
                break
            prev = row["entry_hash"]
        if not chains_ok or prev != meta["head"] or len(lines) != meta["count"]:
            chains_ok = False
            break
    chk("memory_chains_crypto_valid", chains_ok and total_chain_rows > 0, f"verified_rows={total_chain_rows}")

    # 5. Independent re-execution of ALL 5,760 sealed events across ALL 5 arms from revealed salts!
    rep = json.loads((B / "E408-R_RUN_REPORT.json").read_text())
    champs = json.loads((cp_dir / "champions_all.json").read_text())
    reexec_ok = True
    comps_ok = True
    evals_checked = 0

    for sname in ("primary", "replication"):
        sval = salts[sname]
        worlds_sealed = [regen_sealed_events(sval, w) for w in range(WORLDS_PER_SALT)]
        per_arm_corr: dict[str, list[int]] = {}
        for arm_name in (
            "GOVERNED_SHARED_MEMORY",
            "UNGOVERNED_SHARED_MEMORY",
            "ISOLATED_AGENTS",
            "GOVERNED_NO_COUNTEREXAMPLES",
            "SINGLE_GENERALIST",
        ):
            rows = champs[sname][arm_name]
            if len(rows) != WORLDS_PER_SALT:
                reexec_ok = False
                break
            tot_corr = tot_fp = tot_fn = 0
            corrs = []
            for w_row in rows:
                widx = int(w_row["world_idx"])
                prog = w_row["champion"]
                if len(prog) > MAX_CLAUSES:
                    reexec_ok = False
                c_ok = fp = fn = 0
                for ev in worlds_sealed[widx]:
                    pred = eval_prog(prog, ev["x"])
                    y = int(ev["y"])
                    evals_checked += 1
                    if pred == y:
                        c_ok += 1
                    elif pred == 1:
                        fp += 1
                    else:
                        fn += 1
                if c_ok != int(w_row["sealed_correct"]):
                    reexec_ok = False
                tot_corr += c_ok
                tot_fp += fp
                tot_fn += fn
                corrs.append(c_ok)
            per_arm_corr[arm_name] = corrs
            s_rep = rep["sets"][sname]["summaries"][arm_name]
            if (
                s_rep["sealed_correct"] != tot_corr
                or s_rep["sealed_fp"] != tot_fp
                or s_rep["sealed_fn"] != tot_fn
                or abs(s_rep["sealed_accuracy"] - round(tot_corr / (WORLDS_PER_SALT * 120), 6)) > 1e-9
            ):
                reexec_ok = False

        # Re-verify paired comparisons & exact sign test p-values
        pairs = [
            ("governed_vs_isolated", "GOVERNED_SHARED_MEMORY", "ISOLATED_AGENTS"),
            ("governed_vs_ungoverned", "GOVERNED_SHARED_MEMORY", "UNGOVERNED_SHARED_MEMORY"),
            ("governed_vs_no_cx", "GOVERNED_SHARED_MEMORY", "GOVERNED_NO_COUNTEREXAMPLES"),
            ("governed_vs_single", "GOVERNED_SHARED_MEMORY", "SINGLE_GENERALIST"),
        ]
        for cname, a, b in pairs:
            ca, cb = per_arm_corr[a], per_arm_corr[b]
            wins = sum(1 for x, y in zip(ca, cb) if x > y)
            losses = sum(1 for x, y in zip(ca, cb) if x < y)
            ties = len(ca) - wins - losses
            delta = round(
                rep["sets"][sname]["summaries"][a]["sealed_accuracy"]
                - rep["sets"][sname]["summaries"][b]["sealed_accuracy"],
                6,
            )
            pval = round(sign_test_p(wins, losses), 10)
            rc = rep["sets"][sname]["comparisons"][cname]
            if (
                rc["world_wins"] != wins
                or rc["world_losses"] != losses
                or rc["world_ties"] != ties
                or abs(rc["delta_acc"] - delta) > 1e-9
                or abs(rc["sign_test_p"] - pval) > 1e-12
            ):
                comps_ok = False

    chk("sealed_ast_reexecution_exact", reexec_ok and evals_checked == 28800, f"ast_evals={evals_checked}")
    chk("paired_statistics_exact", comps_ok, "8 paired sign tests")

    # 6. Re-derive hypotheses H1-H7 and overall verdict
    p, r = rep["sets"]["primary"], rep["sets"]["replication"]
    both = lambda fn: bool(fn(p)) and bool(fn(r))
    exp_h = {
        "H1_compounding_bounded_rsi": "SUPPORTED"
        if both(lambda s: s["summaries"]["GOVERNED_SHARED_MEMORY"]["gain_g0_to_g4"] >= 0.25
                and s["summaries"]["GOVERNED_SHARED_MEMORY"]["positive_steps"] >= 2)
        else "NOT_SUPPORTED",
        "H2_shared_beats_isolated": "SUPPORTED"
        if both(lambda s: s["comparisons"]["governed_vs_isolated"]["delta_acc"] >= 0.15
                and s["comparisons"]["governed_vs_isolated"]["sign_test_p"] < 0.01)
        else "NOT_SUPPORTED",
        "H3_governance_defeats_poisoning": "SUPPORTED"
        if both(lambda s: s["comparisons"]["governed_vs_ungoverned"]["delta_acc"] >= 0.20
                and s["comparisons"]["governed_vs_ungoverned"]["sign_test_p"] < 0.01
                and s["summaries"]["GOVERNED_SHARED_MEMORY"]["poison_admitted_total"] == 0
                and s["summaries"]["UNGOVERNED_SHARED_MEMORY"]["poison_admitted_total"] > 0)
        else "NOT_SUPPORTED",
        "H4_counterexamples_add_gain": "SUPPORTED"
        if both(lambda s: s["comparisons"]["governed_vs_no_cx"]["delta_acc"] >= 0.05
                and s["comparisons"]["governed_vs_no_cx"]["sign_test_p"] < 0.01)
        else "NOT_SUPPORTED",
        "H5_crypto_and_authority_firewall": "SUPPORTED"
        if both(lambda s: s["security_probes"]["all_passed"]
                and s["summaries"]["GOVERNED_SHARED_MEMORY"]["authority_firewall_blocks"] == WORLDS_PER_SALT * GENS
                and s["summaries"]["GOVERNED_SHARED_MEMORY"]["min_distinct_pids_per_world"] >= 4)
        else "NOT_SUPPORTED",
    }
    h6_ok = all(v == "SUPPORTED" for v in exp_h.values())
    exp_h["H6_cross_salt_replication"] = "SUPPORTED" if h6_ok else "NOT_SUPPORTED"
    exp_h["H7_external_review"] = "BLOCKED"
    exp_verdict = "GOVERNED_SHARED_MEMORY_RSI_SUPPORTED" if h6_ok else "GOVERNED_SHARED_MEMORY_RSI_NOT_SUPPORTED"

    got_h = {k: v["verdict"] for k, v in rep["hypotheses"].items()}
    chk("hypotheses_match_recomputation", got_h == exp_h, f"h_count={len(got_h)}")
    chk("verdict_matches_rule", rep.get("verdict") == exp_verdict == rep["finding"]["verdict"], exp_verdict)

    # 7. Headline, resources, acceptance, external review, reports consistency
    hl = rep["finding"]["headline"]
    chk(
        "headline_consistent",
        hl.get("verdict") == exp_verdict
        and hl.get("worlds_total") == 48
        and hl.get("sealed_events_total") == 5760
        and hl.get("primary_governed_acc") == p["summaries"]["GOVERNED_SHARED_MEMORY"]["sealed_accuracy"]
        and hl.get("replication_governed_acc") == r["summaries"]["GOVERNED_SHARED_MEMORY"]["sealed_accuracy"]
        and hl.get("governed_poison_admitted") == (
            p["summaries"]["GOVERNED_SHARED_MEMORY"]["poison_admitted_total"]
            + r["summaries"]["GOVERNED_SHARED_MEMORY"]["poison_admitted_total"]
        )
        and man.get("headline", {}).get("verdict") == exp_verdict,
        "report+manifest headline",
    )
    chk(
        "law_no_authority_from_memory",
        "authority firewall" in rep["finding"].get("law", "").lower()
        and "memory grants authority" not in rep["finding"].get("law", "").lower(),
        "law checked",
    )
    res = rep.get("resources", {})
    chk("zero_model_calls", res.get("model_calls") == 0 and float(res.get("api_spend_usd", -1)) == 0.0, str(res))

    ext = json.loads((B / "E408-R_EXTERNAL_REVIEW_STATUS.json").read_text())
    chk("external_review_honest", ext.get("status") == "NOT_OBTAINED" and rep.get("external_review") == "NOT_OBTAINED", "NOT_OBTAINED")

    acc = json.loads((B / "E408-R_ACCEPTANCE_REGISTRY.json").read_text())
    chk("acceptance_registry_consistent", acc.get("verdict") == exp_verdict and acc.get("hypotheses") == exp_h, "acceptance match")

    fin_md = (B / "E408-R_FINAL_REPORT.md").read_text()
    pub_md = (B / "E408-R_PUBLIC_SUMMARY.md").read_text()
    chk("final_report_consistent", f"**Preregistered verdict: {exp_verdict}.**" in fin_md and "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL" in fin_md, "final report")
    chk("public_summary_consistent", exp_verdict in pub_md and "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL" in pub_md, "public summary")

    failed = [c for c in checks if not c[1]]
    for name, ok, det in checks:
        print(f"{'PASS' if ok else 'FAIL'} {name}: {det}")
    print(f"{len(checks) - len(failed)}/{len(checks)} checks passed")
    return 0 if not failed else 1


if __name__ == "__main__":
    raise SystemExit(main())
