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

ZERO imports from `cain.*` — verifies manifest SHA-256s, RFC-6962-style binary Merkle root,
Ed25519 signature, zero private-path/secret leakage, preregistration freeze + 5-salt commitments,
independent pure-Python re-execution of `perm_cipher`, `stack_vm`, `grid_ca`, and `bool_circuit`
witnesses, independent recalculation of primary RSI McNemar & Causal BMA statistics from raw
arrays, 15-subsystem bus, 12 continuity drills, and G01–G23 acceptance registry consistency.
"""
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 = list(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 == "ca_rot_l": cur = cur[1:] + cur[:1]
        elif op == "ca_rot_r": cur = cur[-1:] + cur[:-1]
        elif op == "ca_add_r": cur = [(cur[i] + cur[(i + 1) % 6]) % 5 for i in range(6)]
        elif op == "ca_sub_l": cur = [(cur[i] - cur[(i - 1) % 6]) % 5 for i in range(6)]
        elif op == "ca_inc_even": cur = [(cur[i] + (1 if i % 2 == 0 else 0)) % 5 for i in range(6)]
        elif op == "ca_rev": cur = list(reversed(cur))
        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 _binom_cdf_upper(k: int, n: int) -> float:
    return 1.0 if n <= 0 else 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 / "E258_MANIFEST.json", bundle_dir / "E258_SIGNED_BODY.json", bundle_dir / "E258_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.e258.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) >= 16
    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") == "E258")
    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 / "E258_RUN_REPORT.json").read_text("utf-8"))
    reg = json.loads((bundle_dir / "E258_ACCEPTANCE_REGISTRY.json").read_text("utf-8"))
    freeze = json.loads((bundle_dir / "E258_PREREGISTRATION_FREEZE.json").read_text("utf-8"))
    prereg = json.loads((bundle_dir / "E258_PREREGISTRATION.json").read_text("utf-8"))
    salts_rev = json.loads((bundle_dir / "E258_SALTS_REVEALED.json").read_text("utf-8"))
    wits_obj = json.loads((bundle_dir / "E258_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 / "E258_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_sandbox", bool(rr.get("track_h_governance", {}).get("all_passed")))
    rec("continuity_12_drills", bool(rr.get("continuity", {}).get("all_passed") and rr.get("continuity", {}).get("total") == 12))

    wits = wits_obj.get("witnesses", [])
    w_ok = len(wits) >= 3
    reexec = 0
    for w in wits:
        dom, prog = w["domain"], w["witness"]
        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"])
        else:
            ok_w = False
        if ok_w: reexec += 1
        else: w_ok = False
    rec("witnesses_independently_reexecuted", w_ok, f"{reexec}/{len(wits)}")

    salts = ["salt_main", "salt_rep1", "salt_rep2"]
    tb = rr["raw_tracks"]["track_b_rsi"]
    ra = sum((tb[s]["arms"]["e258_island_mitm_recursive_ast"]["hits"] for s in salts), [])
    rb = sum((tb[s]["arms"]["frozen_e248_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_e248"]
    rec("rsi_primary_mcnemar_recalculated", cr["wins"] == n10 and cr["losses"] == n01 and abs(cr["p_one_sided"] - p_calc) < 1e-9)

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

    gates = reg.get("gates", [])
    counts_calc = {k: sum(1 for g in gates if g["status"] == k) for k in ("PASS", "PARTIAL", "FAIL", "BLOCKED")}
    rec("acceptance_registry_g01_g23_complete", [g["id"] for g in gates] == [f"G{i:02d}" for i in range(1, 24)] and counts_calc == reg.get("counts"))
    rec("external_audit_honestly_partial", next((g for g in gates if g["id"] == "G22"), {}).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.e258.verify.v1", "ok": len(failed) == 0, "checks": len(checks), "passed": passed, "failed": failed, "witnesses_reapplied": reexec, "merkle_root": calc_mr, "verdict": rr.get("verdict")}


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(json.dumps({"ok": False, "error": "usage: verify_e258_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)
