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

Independently verifies:
  1. Zero leaked engine source in the bundle
  2. File SHA-256 hashes, binary Merkle root, canonical signed body, Ed25519 manifest signature
  3. Preregistration freeze hash & blind salt commitments
  4. Remote-fetched cross-host epoch logs from 45.76.169.191 (Ed25519 entry sigs, hash chains,
     per-epoch Merkle inclusion proofs, epoch root chaining, epoch header Ed25519 signatures,
     PBFT receipt verdicts, old-epoch valid after rotation, wrong-epoch rejected)
  5. AST safety check + complete independent Python execution of EVERY promoted pipeline across
     all 40 worlds x 4 arms x 40 sealed test cases (= 6,400 sealed Python pipeline executions)
     regenerated directly from the revealed salts
  6. Exact recomputation of all paired sign-test p-values, H1-H7 verdicts, headline, acceptance
     registry, final report, public summary, and zero-model-call attestation.
"""
from __future__ import annotations

import ast
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 = {
    "E416-R_MANIFEST.json", "E416-R_SIGNED_BODY.json", "E416-R_VERIFICATION_RESULTS.json",
    "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E416-R_OMEGA_SEAL.json",
    "E416-R_TAMPER_RESULTS.json",
}
STAGES = ("alpha", "beta", "gamma", "delta")
TAGS_ALL = ("pay", "ops", "sec", "net", "ml")
WORLDS_PER_SALT = 20
GENS = 4
FORBIDDEN_NODES = (
    ast.Import, ast.ImportFrom, ast.While, ast.With, ast.AsyncWith, ast.AsyncFor,
    ast.AsyncFunctionDef, ast.ClassDef, ast.Global, ast.Nonlocal, ast.Lambda, ast.Try, ast.Raise,
)
FORBIDDEN_CALLS = {
    "eval", "exec", "compile", "open", "__import__", "getattr", "setattr", "delattr",
    "globals", "locals", "vars", "dir", "breakpoint", "input", "type", "object",
    "super", "memoryview", "bytearray",
}
SAFE_BUILTINS = {
    "len": len, "min": min, "max": max, "sum": sum, "sorted": sorted,
    "int": int, "str": str, "bool": bool, "dict": dict, "list": list,
    "tuple": tuple, "set": set, "abs": abs, "range": range,
    "isinstance": isinstance, "enumerate": enumerate, "True": True, "False": False, "None": None,
}


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_files(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 ep_leaf(h: str) -> str:
    return sha(("leaf|" + h).encode())


def ep_node(l: str, r: str) -> str:
    return sha(("node|" + l + r).encode())


def ep_root(hs: list[str]) -> str:
    lv = [ep_leaf(h) for h in hs]
    if not lv:
        return sha(b"")
    while len(lv) > 1:
        lv = [ep_node(lv[i], lv[i + 1]) if i + 1 < len(lv) else lv[i] for i in range(0, len(lv), 2)]
    return lv[0]


def ep_verify(h: str, path: list[list[str]], rt: str) -> bool:
    x = ep_leaf(h)
    for side, sib in path:
        x = ep_node(sib, x) if side == "L" else ep_node(x, sib)
    return x == rt


def ast_safe(src: str) -> bool:
    try:
        tree = ast.parse(src)
    except SyntaxError:
        return False
    for node in ast.walk(tree):
        if isinstance(node, FORBIDDEN_NODES):
            return False
        if isinstance(node, ast.Attribute) and (node.attr.startswith("__") or node.attr.endswith("__")):
            return False
        if isinstance(node, ast.Name) and (node.id.startswith("__") or node.id in FORBIDDEN_CALLS):
            return False
    return True


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


def gt_pipeline(rows, spec):
    s0 = []
    for r in rows:
        val, tag = r.get("val"), r.get("tag")
        if val is None or not isinstance(tag, str):
            continue
        t = tag.strip().lower()
        if not t:
            continue
        v = spec["lo"] if val < spec["lo"] else (spec["hi"] if val > spec["hi"] else val)
        s0.append({"id": str(r["id"]), "val": int(v), "tag": t, "weight": int(r.get("weight", 0))})
    allowed = set(spec["allowed"])
    keep_max = spec["dedup_mode"] == "max"
    best = {}
    for r in s0:
        if r["val"] >= spec["min_v"] and r["tag"] in allowed:
            rid = r["id"]
            if rid not in best or ((keep_max and r["val"] > best[rid]["val"]) or ((not keep_max) and r["val"] < best[rid]["val"])):
                best[rid] = dict(r)
    s1 = [best[k] for k in sorted(best.keys())]
    s2 = []
    for r in s1:
        raw = r["val"] * spec["mult"] + r["weight"] * spec["bonus"]
        nr = dict(r)
        nr["score"] = int(spec["cap"] if raw > spec["cap"] else raw)
        s2.append(nr)
    if not s2:
        return []
    ordered = sorted(s2, key=(lambda x: (-x["score"], x["id"])) if spec["sort_desc"] else (lambda x: (x["score"], x["id"])))
    return [x["id"] for x in ordered[: spec["top_k"]]]


def regen_sealed(salt: str, widx: int) -> list[dict[str, Any]]:
    r = rng_for("e416r-spec", salt, widx)
    spec = {
        "lo": r.choice([0, 5, 10]), "hi": r.choice([80, 100, 120]),
        "min_v": r.choice([20, 25, 30]), "allowed": sorted(r.sample(TAGS_ALL, 3)),
        "dedup_mode": r.choice(["max", "min"]), "mult": r.choice([2, 3, 4]),
        "bonus": r.choice([1, 2, 3]), "cap": r.choice([180, 220, 260]),
        "sort_desc": r.choice([True, False]), "top_k": r.choice([2, 3, 4]),
    }

    def happy(rg, n=5):
        rows, used = [], set()
        for i in range(n):
            rid = f"r{i}_{rg.randint(10, 99)}"
            while rid in used:
                rid = f"r{i}_{rg.randint(10, 99)}"
            used.add(rid)
            val = min(rg.choice([spec["min_v"] + 5, spec["min_v"] + 10, max(spec["lo"] + 2, spec["min_v"] - 5)]), spec["hi"] - 5)
            rows.append({"id": rid, "val": val, "tag": rg.choice(list(TAGS_ALL)), "weight": rg.randint(0, 5)})
        return rows

    def edge(stage, rg):
        base = happy(rg, n=4)
        t0 = spec["allowed"][0]
        if stage == "alpha":
            base += [
                {"id": "e_ws", "val": spec["min_v"] + 12, "tag": "   ", "weight": 2},
                {"id": "e_pad", "val": spec["lo"] - 15, "tag": f"  {t0.upper()} ", "weight": 1},
                {"id": "e_hi", "val": spec["hi"] + 50, "tag": t0, "weight": 2},
                {"id": "e_none", "val": None, "tag": t0, "weight": 1},
            ]
        elif stage == "beta":
            base += [
                {"id": "e_eq", "val": spec["min_v"], "tag": t0, "weight": 3},
                {"id": "e_dup", "val": spec["min_v"] + 8, "tag": t0, "weight": 2},
                {"id": "e_dup", "val": spec["min_v"] + 22, "tag": t0, "weight": 2},
            ]
        elif stage == "gamma":
            base += [
                {"id": "e_cap1", "val": spec["hi"], "tag": t0, "weight": 30},
                {"id": "e_cap2", "val": spec["hi"] - 5, "tag": t0, "weight": 25},
            ]
        else:
            v = spec["min_v"] + 10
            base = [
                {"id": "z_tie", "val": v, "tag": t0, "weight": 4},
                {"id": "a_tie", "val": v, "tag": t0, "weight": 4},
                {"id": "m_tie", "val": v, "tag": t0, "weight": 4},
                {"id": "b_low", "val": spec["min_v"] + 2, "tag": t0, "weight": 1},
            ]
        return base

    rs = rng_for("e416r-sealed", salt, widx)
    out = []
    for i in range(40):
        if i < 8:
            raw = happy(rs, n=6)
        elif i == 38:
            raw = []
        elif i == 39:
            raw = edge("alpha", rs)[:4] + edge("beta", rs)[-3:] + edge("gamma", rs)[-2:] + edge("delta", rs)[:3]
        else:
            raw = edge(STAGES[i % 4], rs)
        out.append({"in": raw, "out": gt_pipeline(raw, spec)})
    return out


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_e416r_offline.py <bundle_dir>")
        return 2
    B = Path(sys.argv[1]).resolve()
    checks: list[tuple[str, bool, str]] = []
    chk = lambda n, ok, d="": checks.append((n, bool(ok), d))

    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_e416r_offline.py"], f"py={py_files}")

    man = json.loads((B / "E416-R_MANIFEST.json").read_text())
    chk("manifest_mirror_match", man == json.loads((B / "MANIFEST.json").read_text()), "MANIFEST match")
    actual = 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)
    chk("file_hashes_match", man.get("files") == {str(p.relative_to(B)): sha(p.read_bytes()) for p in actual}, f"files={len(actual)}")
    mk = merkle_files(actual)
    chk("merkle_root_match", man.get("merkle_root") == mk == (B / "MERKLE_ROOT.txt").read_text().strip(), mk[:16])

    sb = (B / "E416-R_SIGNED_BODY.json").read_bytes()
    chk("signed_body_canonical", sb == canon({k: v for k, v in man.items() if k != "signature"}), "canonical")
    sig_ok = False
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), sb)
        sig_ok = True
    except Exception:
        sig_ok = False
    chk("manifest_signature_valid", sig_ok, str(man.get("pubkey_ed25519", ""))[:16])

    pre_b = (B / "E416-R_PREREGISTRATION.json").read_bytes()
    pre = json.loads(pre_b)
    frz = json.loads((B / "E416-R_PREREGISTRATION_FREEZE.json").read_text())
    chk("prereg_freeze_hash", frz.get("preregistration_sha256") == sha(pre_b), frz.get("preregistration_sha256", "")[:16])

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

    # Cross-host PBFT epoch verification on remote logs exported from 45.76.169.191
    cp_dir = B / "checkpoints"
    remote_ok = True
    remote_rows_total = 0
    for sname in ("primary", "replication"):
        ep_meta = json.loads((cp_dir / f"remote_{sname}_epochs.json").read_text())
        entries = [json.loads(l) for l in (cp_dir / f"remote_{sname}_log.jsonl").read_text().splitlines() if l.strip()]
        pubs = ep_meta["pubs"]
        headers = ep_meta["headers"]
        proofs = ep_meta["proofs"]
        prev = "0" * 64
        nonces = set()
        ep_pos = {ep: 0 for ep in range(1, GENS + 1)}
        for idx, e in enumerate(entries, 1):
            remote_rows_total += 1
            if (
                e.get("seq") != idx or e.get("prev_hash") != prev or e.get("nonce") in nonces
                or e.get("grants_authority") is not False or e.get("executable") is not False
            ):
                remote_ok = False
                break
            nonces.add(e["nonce"])
            body = {
                "schema": e["schema"], "tenant": e["tenant"], "seq": e["seq"], "epoch": e["epoch"],
                "agent": e["agent"], "kind": e["kind"], "payload": e["payload"],
                "uncertainty": round(float(e["uncertainty"]), 6), "verification": e["verification"],
                "nonce": e["nonce"], "prev_hash": e["prev_hash"], "created_at": e["created_at"],
            }
            bb, sb_e = canon(body), bytes.fromhex(e["sig"])
            if sha(bb + sb_e) != e["entry_hash"]:
                remote_ok = False
                break
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(sb_e, bb)
            except Exception:
                remote_ok = False
                break
            ep = int(e["epoch"])
            pos = ep_pos[ep]
            ep_pos[ep] += 1
            if not ep_verify(e["entry_hash"], proofs[str(ep)][pos], headers[ep - 1]["root"]):
                remote_ok = False
                break
            prev = e["entry_hash"]
        pr = ""
        for h in headers:
            chunk = [e["entry_hash"] for e in entries if int(e["epoch"]) == int(h["epoch"])]
            bh = {k: v for k, v in h.items() if k not in ("sig", "receipt", "receipt_verify")}
            if ep_root(chunk) != h["root"] or h["prev_root"] != pr or h["count"] != len(chunk) or h["receipt_verify"] != "NOTARIZED":
                remote_ok = False
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(h["signer_pubkey"])).verify(bytes.fromhex(h["sig"]), canon(bh))
            except Exception:
                remote_ok = False
            pr = h["root"]
        if not ep_verify(entries[0]["entry_hash"], proofs["1"][0], headers[0]["root"]):
            remote_ok = False
        if ep_verify(entries[0]["entry_hash"], proofs["1"][0], headers[-1]["root"]):
            remote_ok = False
    chk("cross_host_remote_epochs_valid", remote_ok and remote_rows_total > 0, f"remote_rows={remote_rows_total}, 8 PBFT epochs")

    # Independent AST safety check + full Python execution of ALL 6,400 sealed pipeline tests!
    rep = json.loads((B / "E416-R_RUN_REPORT.json").read_text())
    pipes = json.loads((cp_dir / "pipelines_all.json").read_text())
    reexec_ok = True
    ast_ok = True
    comps_ok = True
    evals_checked = 0

    for sname in ("primary", "replication"):
        sealed_by_w = [regen_sealed(salts[sname], w) for w in range(WORLDS_PER_SALT)]
        per_arm_pass: dict[str, list[int]] = {}
        for arm_name in ("GOVERNED_SHARED_MEMORY", "GOVERNED_NO_COUNTEREXAMPLES", "ISOLATED_AGENTS", "UNGOVERNED_SHARED_MEMORY"):
            rows = pipes[sname][arm_name]
            if len(rows) != WORLDS_PER_SALT:
                reexec_ok = False
                break
            tot_p = 0
            plist = []
            for r_w in rows:
                widx = int(r_w["world_idx"])
                src = r_w["pipeline_source"]
                if not ast_safe(src):
                    ast_ok = False
                    reexec_ok = False
                    continue
                ns: dict[str, Any] = {"__builtins__": SAFE_BUILTINS}
                exec(compile(src, "<verify_e416r>", "exec"), ns, ns)
                fn = ns["run_pipeline"]
                passed = 0
                for tc in sealed_by_w[widx]:
                    evals_checked += 1
                    try:
                        out = fn(json.loads(json.dumps(tc["in"])))
                        if out == tc["out"]:
                            passed += 1
                    except Exception:
                        pass
                if passed != int(r_w["sealed_passed"]):
                    reexec_ok = False
                tot_p += passed
                plist.append(passed)
            per_arm_pass[arm_name] = plist
            s_rep = rep["sets"][sname]["summaries"][arm_name]
            if s_rep["sealed_passed"] != tot_p or abs(s_rep["sealed_pass_rate"] - round(tot_p / (WORLDS_PER_SALT * 40), 6)) > 1e-9:
                reexec_ok = False

        for cname, a, b in [
            ("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"),
        ]:
            pa, pb = per_arm_pass[a], per_arm_pass[b]
            w = sum(1 for x, y in zip(pa, pb) if x > y)
            l = sum(1 for x, y in zip(pa, pb) if x < y)
            t = len(pa) - w - l
            delta = round(rep["sets"][sname]["summaries"][a]["sealed_pass_rate"] - rep["sets"][sname]["summaries"][b]["sealed_pass_rate"], 6)
            pv = round(sign_test_p(w, l), 10)
            rc = rep["sets"][sname]["comparisons"][cname]
            if rc["world_wins"] != w or rc["world_losses"] != l or rc["world_ties"] != t or abs(rc["delta_rate"] - delta) > 1e-9 or abs(rc["sign_test_p"] - pv) > 1e-12:
                comps_ok = False

    chk("all_promoted_pipelines_ast_safe", ast_ok, "160 pipelines AST-checked")
    chk("sealed_python_reexecution_exact", reexec_ok and evals_checked == 6400, f"python_evals={evals_checked}")
    chk("paired_statistics_exact", comps_ok, "6 paired sign tests")

    p, q = rep["sets"]["primary"], rep["sets"]["replication"]
    both = lambda fn: bool(fn(p)) and bool(fn(q))
    exp_h = {
        "H1_compounding_code_rsi": "SUPPORTED" if both(lambda s: s["summaries"]["GOVERNED_SHARED_MEMORY"]["gain_g0_to_g4"] >= 0.60 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_rate"] >= 0.50 and s["comparisons"]["governed_vs_isolated"]["sign_test_p"] < 0.01) else "NOT_SUPPORTED",
        "H3_governance_defeats_code_poisoning": "SUPPORTED" if both(lambda s: s["comparisons"]["governed_vs_ungoverned"]["delta_rate"] >= 0.50 and s["comparisons"]["governed_vs_ungoverned"]["sign_test_p"] < 0.01 and s["summaries"]["GOVERNED_SHARED_MEMORY"]["poison_admitted_total"] == 0 and s["summaries"]["GOVERNED_SHARED_MEMORY"]["ast_blocked_total"] == WORLDS_PER_SALT * GENS and s["summaries"]["UNGOVERNED_SHARED_MEMORY"]["poison_admitted_total"] > 0) else "NOT_SUPPORTED",
        "H4_counterexample_code_repair_gain": "SUPPORTED" if both(lambda s: s["comparisons"]["governed_vs_no_cx"]["delta_rate"] >= 0.20 and s["comparisons"]["governed_vs_no_cx"]["sign_test_p"] < 0.01) else "NOT_SUPPORTED",
        "H5_crypto_ast_firewall_and_pids": "SUPPORTED" if both(lambda s: s["security_probes"]["all_passed"] and s["summaries"]["GOVERNED_SHARED_MEMORY"]["firewall_blocks_total"] == WORLDS_PER_SALT * GENS and s["summaries"]["GOVERNED_SHARED_MEMORY"]["min_distinct_pids_per_world"] == 5) else "NOT_SUPPORTED",
        "H6_cross_host_pbft_epochs": "SUPPORTED" if both(lambda s: bool(s["cross_host_pbft"]["all_ok"])) else "NOT_SUPPORTED",
        "H7_external_review": "BLOCKED",
    }
    ok_all = all(exp_h[k] == "SUPPORTED" for k in exp_h if k != "H7_external_review")
    exp_v = "GOVERNED_CODE_RSI_CROSSHOST_SUPPORTED" if ok_all else "GOVERNED_CODE_RSI_CROSSHOST_NOT_SUPPORTED"

    chk("hypotheses_match_recomputation", {k: v["verdict"] for k, v in rep["hypotheses"].items()} == exp_h, "7 hypotheses")
    chk("verdict_matches_rule", rep.get("verdict") == exp_v == rep["finding"]["verdict"], exp_v)
    hl = rep["finding"]["headline"]
    chk("headline_consistent", hl.get("verdict") == exp_v and hl.get("worlds_total") == 40 and hl.get("sealed_cases_total") == 1600 and hl.get("primary_governed_rate") == p["summaries"]["GOVERNED_SHARED_MEMORY"]["sealed_pass_rate"] and man.get("headline", {}).get("verdict") == exp_v, "headline")
    chk("law_no_authority_from_memory", "without ever granting execution authority from memory" in rep["finding"].get("law", "").lower() and "memory grants authority" not in rep["finding"].get("law", "").lower(), "law")
    chk("zero_model_calls", rep.get("resources", {}).get("model_calls") == 0 and float(rep.get("resources", {}).get("api_spend_usd", -1)) == 0.0, "0 calls")
    chk("external_review_honest", json.loads((B / "E416-R_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED" and rep.get("external_review") == "NOT_OBTAINED", "NOT_OBTAINED")
    acc = json.loads((B / "E416-R_ACCEPTANCE_REGISTRY.json").read_text())
    chk("acceptance_registry_consistent", acc.get("verdict") == exp_v and acc.get("hypotheses") == exp_h, "acceptance")
    chk("final_report_consistent", f"**Preregistered verdict: {exp_v}.**" in (B / "E416-R_FINAL_REPORT.md").read_text() and "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL" in (B / "E416-R_FINAL_REPORT.md").read_text(), "final report")
    chk("public_summary_consistent", exp_v in (B / "E416-R_PUBLIC_SUMMARY.md").read_text() and "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL" in (B / "E416-R_PUBLIC_SUMMARY.md").read_text(), "public summary")

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


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