#!/usr/bin/env python3
"""Standalone zero-CAIN-import offline verifier for CAIN-42 E245 (Gate G19).

Imports ONLY Python standard library + cryptography.
Re-verifies:
  1. Manifest SHA-256 of every listed file (>= 28 deliverables) + binary Merkle root + Ed25519 signature
  2. Preregistration freeze SHA-256 + revealed salt commitments + master commitment
  3. 15-subsystem OrganismEventBus SHA-256 hash chain & full 15/15 connectivity
  4. Governance Ed25519 execution receipts (all 3 stages)
  5. Champion Registry integrity & AST sandbox self-test pass
  6. Independent re-execution of published unseen Domain-7 (`grid_ca`) witnesses on held-out test inputs
  7. Independent recomputation of primary paired McNemar p-values from raw binary hits
  8. G01-G23 Acceptance Registry completeness & honest status discipline (`AGI: NOT ESTABLISHED`, `neural_weight_modification = false`)
  9. Zero private host paths (/root/) or secret key leaks in non-code files

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

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

GENESIS = "0" * 64
SUBSYSTEMS = (
    "A_GENERAL_CORE", "B_REASONING_PLANNING", "C_CAUSAL_WORLD_MODEL", "D_KNOWLEDGE_ORGANISM",
    "E_CONTINUAL_LEARNING", "F_CAPABILITY_ACQUISITION", "G_CROSS_DOMAIN_TRANSFER",
    "H_SCIENTIFIC_DISCOVERY", "I_RECURSIVE_SELF_IMPROVEMENT", "J_COLLECTIVE_INTELLIGENCE",
    "K_AUTONOMOUS_ENGINEERING", "L_INDEPENDENT_EVALUATION", "M_LONG_HORIZON_PERSISTENCE",
    "N_GOVERNANCE_CONSTITUTION", "O_EVIDENCE_REPRODUCIBILITY",
)
CA_MOD, CA_LEN = 5, 6
CA_PRIMS = {
    "shl": lambda s: s[1:] + s[:1],
    "shr": lambda s: s[-1:] + s[:-1],
    "nad": lambda s: tuple((s[i] + s[(i + 1) % CA_LEN]) % CA_MOD for i in range(CA_LEN)),
    "ndf": lambda s: tuple((s[i] - s[(i - 1) % CA_LEN]) % CA_MOD for i in range(CA_LEN)),
    "crev": lambda s: s[::-1],
    "ievn": lambda s: tuple((s[i] + (1 if i % 2 == 0 else 0)) % CA_MOD for i in range(CA_LEN)),
    "cm2": lambda s: tuple((s[i] * 2) % CA_MOD for i in range(CA_LEN)),
    "swh": lambda s: s[3:] + s[:3],
}


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


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


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


def merkle(hashes) -> str:
    leaves = sorted(hashes)
    if not leaves:
        return sha(b"")
    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]


def replay_grid_ca(prog, st, perm):
    cur = tuple(int(x) % CA_MOD for x in st)
    for op in prog:
        cur = CA_PRIMS[perm[op] if perm else op](cur)
    return list(cur)


def exact_mcnemar_p(a_hits, b_hits):
    ao = sum(1 for a, b in zip(a_hits, b_hits) if a == 1 and b == 0)
    bo = sum(1 for a, b in zip(a_hits, b_hits) if a == 0 and b == 1)
    n = ao + bo
    return 1.0 if n == 0 else sum(math.comb(n, k) for k in range(ao, n + 1)) / (2 ** n)


def verify_bundle(bundle_dir: Path) -> dict:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    checks, failed = [], []

    def chk(name: str, ok: bool, detail: str = ""):
        checks.append({"check": name, "ok": bool(ok), "detail": detail})
        if not ok:
            failed.append(f"{name}: {detail}")

    man_p, sb_p = bundle_dir / "E245_MANIFEST.json", bundle_dir / "E245_SIGNED_BODY.json"
    chk("manifest_exists", man_p.is_file() and sb_p.is_file(), "missing manifest/signed_body")
    if not (man_p.is_file() and sb_p.is_file()):
        return {"schema": "cain42.e245.verify.v1", "ok": False, "checks": len(checks), "passed": 0, "failed": failed}

    man = json.loads(man_p.read_text("utf-8"))
    sb_bytes = sb_p.read_bytes()
    chk("signed_body_matches_manifest", sb_bytes == canon_ascii({k: v for k, v in man.items() if k != "signature"}), "signed body mismatch")

    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), sb_bytes)
        chk("manifest_ed25519_sig", True, man["pubkey_fingerprint"])
    except Exception as ex:
        chk("manifest_ed25519_sig", False, repr(ex))

    listed = man.get("files", {})
    fhashes, all_ok = [], True
    for rel, eh in sorted(listed.items()):
        fp = bundle_dir / rel
        if not fp.is_file():
            all_ok = False; failed.append(f"missing:{rel}"); continue
        ah = sha(fp.read_bytes()); fhashes.append(ah)
        if ah != eh:
            all_ok = False; failed.append(f"hash_mismatch:{rel}")
    chk("all_manifest_file_hashes", all_ok and len(listed) >= 28, f"files={len(listed)}")
    mroot = merkle(fhashes)
    chk("merkle_root_match", mroot == man.get("merkle_root"), mroot[:16])

    pre_p, frz_p, sal_p = bundle_dir / "E245_PREREGISTRATION.json", bundle_dir / "E245_PREREGISTRATION_FREEZE.json", bundle_dir / "E245_SALTS_REVEALED.json"
    pre, frz, sal = json.loads(pre_p.read_text("utf-8")), json.loads(frz_p.read_text("utf-8")), json.loads(sal_p.read_text("utf-8"))
    chk("prereg_freeze_sha256", sha(pre_p.read_bytes()) == frz.get("preregistration_sha256"), "freeze mismatch")
    sok = all(sha(bytes.fromhex(v)) == pre["salt_commitments_sha256"].get(k) for k, v in sal["salts"].items())
    mcalc = sha(json.dumps({k: sha(bytes.fromhex(v)) for k, v in sal["salts"].items()}, sort_keys=True).encode("utf-8"))
    chk("salt_commitments_and_master", sok and mcalc == pre.get("salt_master_commitment_sha256"), f"salts={len(sal['salts'])}")

    rep = json.loads((bundle_dir / "E245_RUN_REPORT.json").read_text("utf-8"))
    chk("status_line_honest", rep.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL", str(rep.get("status")))
    chk("neural_weights_false", rep.get("neural_weight_modification") is False, str(rep.get("neural_weight_modification")))
    chk("prereg_bound_in_report", rep.get("preregistration_sha256") == frz.get("preregistration_sha256"), "report prereg mismatch")
    chk("ast_sandbox_all_rejected", bool(rep.get("ast_sandbox_self_test", {}).get("all_rejected")), "sandbox check")

    # Champion registry check
    creg = json.loads((bundle_dir / "E245_CHAMPION_REGISTRY.json").read_text("utf-8"))
    chk("champion_registry_valid", len(creg.get("champions", [])) == 2 and creg.get("selected_strongest_champion") in ("CHAMPION_E240", "CHAMPION_E243"), str(creg.get("selected_strongest_champion")))

    # Bus chain & 15/15 connectivity
    evts = rep.get("bus_events", [])
    prev, bok, touched = GENESIS, len(evts) > 0, set()
    for e in evts:
        if e["prev_hash"] != prev:
            bok = False; break
        exp = sha(canon({"at": e["at"], "src": e["src"], "dst": e["dst"], "event_type": e["event_type"], "payload_sha256": e["payload_sha256"], "summary": e["summary"], "prev": prev}))
        if e["hash"] != exp:
            bok = False; break
        prev = e["hash"]; touched.add(e["src"]); touched.add(e["dst"])
    chk("bus_hash_chain_and_15_subsystems", bok and all(s in touched for s in SUBSYSTEMS), f"events={len(evts)}, active={len(touched)}/15")

    # Governance receipts Ed25519
    gov = json.loads((bundle_dir / "E245_GOVERNANCE.json").read_text("utf-8"))
    gpub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(gov["governance"]["permit_public_key"]))
    rok, rcnt = True, 0
    for st in gov["governance"]["stages"]:
        rc = dict(st["receipt"]); sig = rc.pop("signature")
        try:
            gpub.verify(bytes.fromhex(sig), canon_ascii(rc)); rcnt += 1
        except Exception:
            rok = False
    chk("governance_receipts_ed25519", rok and rcnt == 3, f"verified={rcnt}/3")

    # Independent re-execution of unseen Domain-7 (`grid_ca`) witnesses
    wits = json.loads((bundle_dir / "E245_WITNESSES.json").read_text("utf-8")).get("witnesses", [])
    wok, wfail = 0, 0
    for w in wits:
        if w["domain"] != "grid_ca":
            continue
        preds = [replay_grid_ca(w["witness"], x, w.get("perm")) for x in w["test_in"]]
        if preds == w["test_out"]:
            wok += 1
        else:
            wfail += 1
    chk("grid_ca_witnesses_reexecuted_offline", wok >= 6 and wfail == 0, f"reapplied={wok}, failed={wfail}")

    # Statistical recomputation from raw binary hits
    td = rep["raw_tracks"]; sn = ("salt_main", "salt_rep1", "salt_rep2")
    p_rsi = exact_mcnemar_p(
        [x for s in sn for x in td["track_abc_rsi_ast"][s]["arms"]["recursive_ast_with_knowledge"]["final_sealed_hits"]],
        [x for s in sn for x in td["track_abc_rsi_ast"][s]["frozen_e243_hits"]],
    )
    chk("stat_recompute_ast_rsi", abs(p_rsi - rep["hypotheses"]["H01_champion_ast_rsi"]["vs_e243"]["p_one_sided"]) < 1e-9, f"p={p_rsi:.3e}")

    p_meta = exact_mcnemar_p(
        [x for s in sn for x in td["track_d_meta"][s]["optimal_hits"]["meta_research_policy"]],
        [x for s in sn for x in td["track_d_meta"][s]["optimal_hits"]["strong_hand_designed"]],
    )
    chk("stat_recompute_meta_research", abs(p_meta - rep["hypotheses"]["H02_meta_research_transfer"]["vs_hand"]["p_one_sided"]) < 1e-9, f"p={p_meta:.3e}")

    # G01-G23 Acceptance Registry
    reg = json.loads((bundle_dir / "E245_ACCEPTANCE_REGISTRY.json").read_text("utf-8"))
    gates = reg.get("gates", [])
    chk("acceptance_registry_g01_g23", [g["id"] for g in gates] == [f"G{i:02d}" for i in range(1, 24)] and all(g["status"] in {"PASS", "PARTIAL", "FAIL", "BLOCKED"} for g in gates), f"gates={len(gates)}")

    # Zero private host paths or secret patterns
    sec_re = re.compile(r"/root/|-----BEGIN [A-Z ]*PRIVATE KEY-----|sk-ant-|sk_live_|\bhf_[A-Za-z0-9]{20,}")
    flagged = [rel for rel in sorted(listed) if not rel.endswith(".py") and sec_re.search((bundle_dir / rel).read_text("utf-8", "replace"))]
    chk("zero_private_paths_or_secrets", len(flagged) == 0, f"flagged={flagged}")

    passed = sum(1 for c in checks if c["ok"])
    return {"schema": "cain42.e245.verify.v1", "ok": len(failed) == 0, "checks": len(checks), "passed": passed, "failed": failed, "witnesses_reapplied": wok, "merkle_root": mroot, "verdict": rep.get("verdict")}


def main():
    if len(sys.argv) < 2:
        print("Usage: verify_e245_offline.py <bundle_dir>", file=sys.stderr); sys.exit(2)
    res = verify_bundle(Path(sys.argv[1]))
    print(json.dumps(res, ensure_ascii=False))
    sys.exit(0 if res["ok"] else 1)


if __name__ == "__main__":
    main()
