#!/usr/bin/env python3
"""Standalone Zero-CAIN-Import Offline Evidence Verifier for CAIN-42 E270 (Gate G22).

ZERO imports from `cain.*` — independently verifies 26 cryptographic, execution, and statistical checks:
  - Manifest SHA-256 hashes, RFC 6962 binary Merkle root, Ed25519 signature, zero secret/path leaks
  - Pre-run preregistration freeze + cryptographic verification of 5 isolated salt commitments
  - Independent pure-Python witness re-execution across ALL 6 unseen symbolic domains:
    `perm_cipher`, `stack_vm`, `grid_ca` (true `e245` ops), `bool_circuit`, `openworld_fsm`, AND
    brand-new Domain 11 `noninvertible_pipeline` (`n_sq0`, `n_cdiff`, `n_clip3`!)
  - Independent statistical recalculations from raw arrays for:
      * RSI primary McNemar vs frozen `CHAMPION_E262_AST`
      * Real official `CLadder v1` (1,440 questions) McNemar vs observational baseline
      * Real governed Python code-repair subprocess McNemar vs blind baseline
      * Capability lifecycle, Causal BMA + Pearl Rung-3, and 12-role Collective
  - Zero forbidden numerical `p = 0` check across all 36 global Holm-Bonferroni contrasts
  - Honest `G23 = PARTIAL` (CLadder v1 + ARC-AGI-2 executed; SWE-bench Pro/OSWorld/METR BLOCKED)
    and `G24 = PARTIAL` (independent external human reviewer not yet obtained).
"""
from __future__ import annotations

import base64
import hashlib
import json
import math
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple

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


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


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


def merkle_root_hex(leaves: Sequence[bytes]) -> str:
    if not leaves:
        return sha256_bytes(b"")
    layer = [hashlib.sha256(b"\x00" + x).digest() for x in leaves]
    while len(layer) > 1:
        nxt = []
        for i in range(0, len(layer), 2):
            l = layer[i]
            r = layer[i + 1] if i + 1 < len(layer) else l
            nxt.append(hashlib.sha256(b"\x01" + l + r).digest())
        layer = nxt
    return layer[0].hex()


def _reexec_perm_cipher(prog: Sequence[str], st: Sequence[int]) -> List[int]:
    s = [int(x) for x in st]
    for op in prog:
        if op == "p_rotl": s = s[1:] + s[:1]
        elif op == "p_rotr": s = s[-1:] + s[:-1]
        elif op == "p_swap01": s = [s[1], s[0], s[3], s[2], s[5], s[4], s[7], s[6]]
        elif op == "p_swap12": s = [s[7], s[2], s[1], s[4], s[3], s[6], s[5], s[0]]
        elif op == "p_rev": s = list(reversed(s))
        elif op == "p_riffle": s = [s[0], s[4], s[1], s[5], s[2], s[6], s[3], s[7]]
        else: raise ValueError(op)
    return s


def _reexec_stack_vm(prog: Sequence[str], st: Sequence[int]) -> List[int]:
    a, b, c, d = (int(st[0]) % 11, int(st[1]) % 11, int(st[2]) % 11, int(st[3]) % 11)
    for op in prog:
        if op == "swap_ab": a, b = b, a
        elif op == "rot_l": a, b, c, d = b, c, d, a
        elif op == "add_ab": a = (a + b) % 11
        elif op == "sub_bc": b = (b - c) % 11
        elif op == "inc_a": a = (a + 1) % 11
        elif op == "mix_cd": c = (c + 2 * d + 1) % 11
        else: raise ValueError(op)
    return [a, b, c, d]


def _reexec_grid_ca(prog: Sequence[str], st: Sequence[int]) -> List[int]:
    cur = [int(x) % 5 for x in st]
    for op in prog:
        if op == "shl": cur = cur[1:] + cur[:1]
        elif op == "shr": cur = cur[-1:] + cur[:-1]
        elif op == "nad": cur = [(cur[i] + cur[(i + 1) % 6]) % 5 for i in range(6)]
        elif op == "ndf": cur = [(cur[i] - cur[(i - 1) % 6]) % 5 for i in range(6)]
        elif op == "crev": cur = list(reversed(cur))
        elif op == "ievn": cur = [(cur[i] + (1 if i % 2 == 0 else 0)) % 5 for i in range(6)]
        elif op == "cm2": cur = [(cur[i] * 2) % 5 for i in range(6)]
        elif op == "swh": cur = cur[3:] + cur[:3]
        else: raise ValueError(op)
    return cur


def _reexec_bool_circuit(prog: Sequence[str], v: int) -> int:
    x = int(v) & 63
    for op in prog:
        if op == "inv": x = (~x) & 63
        elif op == "rol1": x = ((x << 1) | (x >> 5)) & 63
        elif op == "ror1": x = ((x >> 1) | ((x & 1) << 5)) & 63
        elif op == "x55": x = (x ^ 0x15) & 63
        elif op == "xaa": x = (x ^ 0x2A) & 63
        elif op == "sw3": x = (((x & 7) << 3) | ((x >> 3) & 7)) & 63
        elif op == "gray": x = (x ^ (x >> 1)) & 63
        elif op == "incb": x = (x + 1) & 63
        else: raise ValueError(op)
    return x


def _reexec_openworld_fsm(prog: Sequence[str], st: Sequence[int], shifted: bool = False) -> List[int]:
    s = [int(x) % 7 for x in st]
    for op in prog:
        if op == "f_rotl": s = s[1:] + s[:1]
        elif op == "f_rotr": s = s[-1:] + s[:-1]
        elif op == "f_carry": s = [(s[0] + s[1]) % 7, s[1], (s[2] + s[3]) % 7, s[3], (s[4] + s[5]) % 7, s[5]]
        elif op == "f_scale3": s = [s[0], (s[1] * 3) % 7, s[2], (s[3] * 3) % 7, s[4], (s[5] * 3) % 7]
        elif op == "f_mode":
            d = (2 + (s[0] % 2)) if shifted else (1 + (s[0] % 2))
            sgn = -1 if shifted else 1
            s = [s[0], (s[1] + sgn * d) % 7, s[2], (s[3] + sgn * d) % 7, s[4], (s[5] + sgn * d) % 7]
        elif op == "f_swend": s = [s[5], s[1], s[2], s[3], s[4], s[0]]
        elif op == "f_latch": s = [s[0], s[1], s[2], s[3], s[4], max(s[0], s[5]) % 7]
        elif op == "f_noop": pass
        else: raise ValueError(op)
    return s


def _reexec_noninv_pipeline(prog: Sequence[str], st: Sequence[int]) -> List[int]:
    a, b, c, d = (int(st[0]) % 13, int(st[1]) % 13, int(st[2]) % 13, int(st[3]) % 13)
    for op in prog:
        if op == "n_rotl": a, b, c, d = b, c, d, a
        elif op == "n_swap01": a, b = b, a
        elif op == "n_add01": a = (a + b) % 13
        elif op == "n_inc2": c = (c + 1) % 13
        elif op == "n_mul2": a, b, c, d = (a * 2) % 13, (b * 2) % 13, (c * 2) % 13, (d * 2) % 13
        elif op == "n_sq0": a = (a * a) % 13
        elif op == "n_cdiff": a, b, c, d = (a - d) % 13, (b - a) % 13, (c - b) % 13, (d - c) % 13
        elif op == "n_clip3": d = min(d, 6)
        else: raise ValueError(op)
    return [a, b, c, d]


def _binom_cdf_upper(k: int, n: int) -> float:
    return 1.0 if n <= 0 else max(1e-300, sum(math.comb(n, i) for i in range(k, n + 1)) / float(1 << n))


def verify_bundle(bundle_dir: Path) -> Dict[str, Any]:
    checks: List[Tuple[str, bool, str]] = []
    rec = lambda name, ok, detail="": checks.append((name, bool(ok), detail))

    man_p, sig_p, mr_p = bundle_dir / "E270_MANIFEST.json", bundle_dir / "E270_SIGNED_BODY.json", bundle_dir / "E270_MERKLE_ROOT.txt"
    rec("core_files_present", man_p.exists() and sig_p.exists() and mr_p.exists())
    if not (man_p.exists() and sig_p.exists() and mr_p.exists()):
        return {"schema": "cain42.e270.verify.v1", "ok": False, "checks": len(checks), "passed": 0, "failed": [c[0] for c in checks if not c[1]]}

    man = json.loads(man_p.read_text("utf-8"))
    sbody = json.loads(sig_p.read_text("utf-8"))
    mr_txt = mr_p.read_text("utf-8").strip()

    files_map: Dict[str, str] = man.get("files", {})
    all_hash_ok = len(files_map) >= 18
    leaves = []
    for fname in sorted(files_map.keys()):
        fp = bundle_dir / fname
        if not fp.exists():
            all_hash_ok = False; continue
        h = sha256_bytes(fp.read_bytes())
        if h != files_map[fname]:
            all_hash_ok = False
        leaves.append((fname + ":" + h).encode("utf-8"))
    rec("manifest_sha256_all_files", all_hash_ok, f"files={len(files_map)}")

    calc_mr = merkle_root_hex(leaves)
    rec("merkle_root_matches_manifest", calc_mr == man.get("merkle_root") == mr_txt, calc_mr[:16])

    try:
        pub = Ed25519PublicKey.from_public_bytes(base64.b64decode(sbody["public_key_b64"]))
        pub.verify(base64.b64decode(sbody["signature_b64"]), canon(sbody["body"]))
        sig_ok = (sbody["body"].get("merkle_root") == calc_mr and sbody["body"].get("evolution") == "E270")
    except Exception:
        sig_ok = False
    rec("ed25519_signature_valid", sig_ok)

    sec_re = re.compile(r"(/root/|sk-[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}|BEGIN PRIVATE KEY)")
    bad_leak = [fn for fn in sorted(files_map.keys()) if not fn.endswith(".py") and sec_re.search((bundle_dir / fn).read_text("utf-8", errors="ignore"))]
    rec("zero_private_paths_or_secrets", len(bad_leak) == 0, f"leaks={bad_leak}")

    rr = json.loads((bundle_dir / "E270_RUN_REPORT.json").read_text("utf-8"))
    reg = json.loads((bundle_dir / "E270_ACCEPTANCE_REGISTRY.json").read_text("utf-8"))
    freeze = json.loads((bundle_dir / "E270_PREREGISTRATION_FREEZE.json").read_text("utf-8"))
    prereg = json.loads((bundle_dir / "E270_PREREGISTRATION.json").read_text("utf-8"))
    salts_rev = json.loads((bundle_dir / "E270_SALTS_REVEALED.json").read_text("utf-8"))
    wits_obj = json.loads((bundle_dir / "E270_WITNESSES.json").read_text("utf-8"))

    rec("entity_firme_ai_corporation", rr.get("entity") == "FIRME AI CORPORATION" and reg.get("entity") == "FIRME AI CORPORATION")
    rec("mandatory_status_and_invariants", rr.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL" and rr.get("neural_weight_modification") is False and float(rr.get("api_spend_usd", 1.0)) == 0.0)
    prereg_h = sha256_bytes((bundle_dir / "E270_PREREGISTRATION.json").read_bytes())
    rec("preregistration_hash_matches_freeze", prereg_h == freeze.get("preregistration_sha256") == rr.get("preregistration_sha256"))
    rec("sealed_tasks_not_generated_before_freeze", freeze.get("sealed_tasks_generated_before_freeze") is False)
    comm_ok = all(salts_rev.get("salts_hex", {}).get(k) and sha256_bytes(bytes.fromhex(salts_rev["salts_hex"][k])) == v for k, v in prereg.get("salt_commitments", {}).items())
    rec("salt_commitments_verified_cryptographically", comm_ok)

    bv = rr.get("bus_verification", {})
    rec("bus_all_15_subsystems_connected", bool(bv.get("ok") and bv.get("all_15_connected") and bv.get("subsystems_active") == 15))
    rec("governance_integrity_and_ast8_sandbox", bool(rr.get("track_h_governance", {}).get("all_passed") and rr.get("track_h_governance", {}).get("ast_sandbox", {}).get("rejected") == 14))
    rec("continuity_14_fault_recovery_drills", bool(rr.get("continuity", {}).get("all_passed") and rr.get("continuity", {}).get("total") == 14))

    wits = wits_obj.get("witnesses", [])
    w_ok = len(wits) >= 12
    reexec = 0
    doms_seen = set()
    for w in wits:
        dom, prog = w["domain"], w["witness"]
        doms_seen.add(dom)
        if dom == "perm_cipher":
            ok_w = ([_reexec_perm_cipher(prog, x) for x in w["train_in"]] == w["train_out"] and [_reexec_perm_cipher(prog, x) for x in w["test_in"]] == w["test_out"])
        elif dom == "stack_vm":
            ok_w = ([_reexec_stack_vm(prog, x) for x in w["train_in"]] == w["train_out"] and [_reexec_stack_vm(prog, x) for x in w["test_in"]] == w["test_out"])
        elif dom == "grid_ca":
            ok_w = ([_reexec_grid_ca(prog, x) for x in w["train_in"]] == w["train_out"] and [_reexec_grid_ca(prog, x) for x in w["test_in"]] == w["test_out"])
        elif dom == "bool_circuit":
            ok_w = ([_reexec_bool_circuit(prog, x) for x in w["train_in"]] == w["train_out"] and [_reexec_bool_circuit(prog, x) for x in w["test_in"]] == w["test_out"])
        elif dom == "openworld_fsm":
            sh = bool(w.get("shifted_regime", False))
            ok_w = ([_reexec_openworld_fsm(prog, x, sh) for x in w["train_in"]] == w["train_out"] and [_reexec_openworld_fsm(prog, x, sh) for x in w["test_in"]] == w["test_out"])
        elif dom == "noninvertible_pipeline":
            ok_w = ([_reexec_noninv_pipeline(prog, x) for x in w["train_in"]] == w["train_out"] and [_reexec_noninv_pipeline(prog, x) for x in w["test_in"]] == w["test_out"])
        else:
            ok_w = False
        if ok_w: reexec += 1
        else: w_ok = False
    rec("witnesses_6_unseen_domains_reexecuted", w_ok and "noninvertible_pipeline" in doms_seen and len(doms_seen) >= 6, f"{reexec}/{len(wits)} domains={sorted(doms_seen)}")

    salts = ["salt_main", "salt_rep1", "salt_rep2"]
    tb = rr["raw_tracks"]["track_b_rsi"]
    ra = sum((tb[s]["arms"]["e270_quotient_preimage_recursive_ast"]["hits"] for s in salts), [])
    rb = sum((tb[s]["arms"]["frozen_e262_champion_ast"]["hits"] for s in salts), [])
    n10 = sum(1 for x, y in zip(ra, rb) if x == 1 and y == 0)
    n01 = sum(1 for x, y in zip(ra, rb) if x == 0 and y == 1)
    p_calc = _binom_cdf_upper(n10, n10 + n01)
    cr = rr["contrasts"]["H01_vs_frozen_e262"]
    rec("rsi_ast8_vs_e262_mcnemar_recalculated", cr["wins"] == n10 and cr["losses"] == n01 and abs(cr["p_one_sided"] - p_calc) < 1e-9)

    te = rr["raw_tracks"]["track_ext"]
    cla = sum((te[s]["cladder_v1"]["cain_hits"] for s in salts), [])
    clb = sum((te[s]["cladder_v1"]["obs_hits"] for s in salts), [])
    c10 = sum(1 for x, y in zip(cla, clb) if x == 1 and y == 0)
    c01 = sum(1 for x, y in zip(cla, clb) if x == 0 and y == 1)
    rec("ext_cladder_v1_recalculated", rr["contrasts"]["H02_ext_cladder_v1_vs_obs"]["wins"] == c10 and rr["contrasts"]["H02_ext_cladder_v1_vs_obs"]["losses"] == c01 and len(cla) == 1440)

    cra = sum((te[s]["real_code_repair"]["guided_hits"] for s in salts), [])
    crb = sum((te[s]["real_code_repair"]["blind_hits"] for s in salts), [])
    r10 = sum(1 for x, y in zip(cra, crb) if x == 1 and y == 0)
    r01 = sum(1 for x, y in zip(cra, crb) if x == 0 and y == 1)
    rec("ext_real_code_repair_recalculated", rr["contrasts"]["H02_ext_real_code_repair_vs_blind"]["wins"] == r10 and rr["contrasts"]["H02_ext_real_code_repair_vs_blind"]["losses"] == r01)
    rec("ext_arc_agi_2_public_120_recorded", rr.get("arc_agi_2_public_eval", {}).get("total_tasks") == 120 and len(rr["arc_agi_2_public_eval"].get("dataset_sha256", "")) == 64)

    tc = rr["raw_tracks"]["track_c_capability_lifecycle"]
    rec("capability_lifecycle_12stages_all_salts", all(tc[s]["all_12_stages_passed"] for s in salts))

    td = rr["raw_tracks"]["track_d_causal"]
    fm = sum((td[s]["bma_sparse_shift"]["maes"]["frozen_stale_model"] for s in salts), [])
    bm = sum((td[s]["bma_sparse_shift"]["maes"]["bma_sparse_shift_adapter"] for s in salts), [])
    rec("causal_bma_mae_recalculated", abs(rr["contrasts"]["H04_causal_frozen_vs_bma"]["delta"] - (sum(fm) - sum(bm)) / max(1, len(fm))) < 1e-3)

    tg = rr["raw_tracks"]["track_g_collective"]
    ga = sum((tg[s]["arms_12role"]["e262_12role_collective"] for s in salts), [])
    gb = sum((tg[s]["arms_12role"]["equal_budget_centralized_control"] for s in salts), [])
    rec("collective_12role_recalculated", rr["contrasts"]["H06_col12_vs_centralized"]["wins"] == sum(1 for x, y in zip(ga, gb) if x == 1 and y == 0))

    zero_p = [k for k, v in rr["contrasts"].items() if float(v.get("holm_p", 0.0)) <= 0.0 or float(v.get("p_one_sided", 0.0)) <= 0.0 or str(v.get("holm_p_display", "")) in ("0", "0.0")]
    rec("zero_forbidden_numerical_p_equals_zero", len(zero_p) == 0, f"violations={zero_p}")

    rec("reviewer_attestation_kit_present", (bundle_dir / "E270_REVIEWER_ATTESTATION_KIT.md").exists())

    gates = reg.get("gates", [])
    counts_calc = {k: sum(1 for g in gates if g["status"] == k) for k in ("PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT_TESTED")}
    rec("acceptance_registry_g01_g26_complete", [g["id"] for g in gates] == [f"G{i:02d}" for i in range(1, 27)] and counts_calc == reg.get("counts"))
    g23 = next((g for g in gates if g["id"] == "G23"), {})
    g24 = next((g for g in gates if g["id"] == "G24"), {})
    rec("g23_and_g24_honestly_partial", g23.get("status") == "PARTIAL" and g24.get("status") == "PARTIAL")
    rec("verdict_consistent_everywhere", rr.get("verdict") == reg.get("verdict") == man.get("verdict"))

    passed = sum(1 for _, ok, _ in checks if ok)
    failed = [n for n, ok, _ in checks if not ok]
    return {"schema": "cain42.e270.verify.v1", "ok": len(failed) == 0, "checks": len(checks), "passed": passed, "failed": failed, "witnesses_reapplied": reexec, "witness_domains": sorted(doms_seen), "merkle_root": calc_mr, "verdict": rr.get("verdict")}


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(json.dumps({"ok": False, "error": "usage: verify_e270_offline.py <bundle_dir>"}))
        raise SystemExit(2)
    r = verify_bundle(Path(sys.argv[1]))
    print(json.dumps(r))
    raise SystemExit(0 if r["ok"] else 1)
