#!/usr/bin/env python3
"""CAIN-42 UNIFIED AGI-RSI ORGANISM APEX — Standalone Offline Verifier.

Python stdlib ONLY. Zero CAIN imports.
Verifies normal, unprivileged (nobody), read-only copy, and rejects corrupted copies.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

CHECKS = 0
FAILURES: list[str] = []


def check(cond: bool, name: str, detail: str = "") -> None:
    global CHECKS
    CHECKS += 1
    print(f"{'PASS' if cond else 'FAIL'} {name}" + (f" {detail}" if detail else ""))
    if not cond:
        FAILURES.append(name)


def sha256_file(p: Path) -> str:
    h = hashlib.sha256()
    with p.open("rb") as fh:
        for ch in iter(lambda: fh.read(65536), b""):
            h.update(ch)
    return h.hexdigest()


def canon_str(o) -> str:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def merkle_root(leaves: list[str]) -> str:
    if not leaves:
        return hashlib.sha256(b"").hexdigest()
    lvl = [hashlib.sha256(b"\x00" + bytes.fromhex(h)).digest() for h in leaves]
    while len(lvl) > 1:
        nxt = []
        for i in range(0, len(lvl), 2):
            nxt.append(hashlib.sha256(b"\x01" + lvl[i] + lvl[i + 1]).digest() if i + 1 < len(lvl) else lvl[i])
        lvl = nxt
    return lvl[0].hex()


def load_json(p: Path):
    return json.loads(p.read_text(encoding="utf-8"))


def load_jsonl(p: Path) -> list[dict]:
    return [json.loads(ln) for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]


def main() -> int:
    root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
    print(f"CAIN-42 APEX offline verifier root={root}")

    man = load_json(root / "MANIFEST.json")
    check(man.get("entity") == "FIRME AI CORPORATION", "manifest_entity")
    check(man.get("agi_status") == "NOT ESTABLISHED", "manifest_agi_honest")
    check(man.get("rsi_status") == "EXPERIMENTAL", "manifest_rsi_honest")
    for entry in man["files"]:
        fp = root / entry["path"]
        check(fp.exists() and sha256_file(fp) == entry["sha256"], f"sha256:{entry['path']}")

    exps = load_jsonl(root / "APEX_EXPERIMENTS.jsonl")
    check(len(exps) == 1200, "unification_1200_evals", str(len(exps)))
    hashes_ok = True
    leaves = []
    for e in exps:
        body = {k: v for k, v in e.items() if k != "record_sha256"}
        if hashlib.sha256(canon_str(body).encode()).hexdigest() != e.get("record_sha256"):
            hashes_ok = False
        leaves.append(e["record_sha256"])
    check(hashes_ok, "all_1200_record_hashes_valid")
    m_calc = merkle_root(leaves)
    snap_signed = load_json(root / "APEX_SNAPSHOT.json")
    snap = snap_signed["snapshot"]
    check(hashlib.sha256(canon_str(snap).encode()).hexdigest() == snap_signed["snapshot_sha256"], "snapshot_sha256_valid")
    check(m_calc == snap["merkle_root"] == man["merkle_root"], "merkle_root_match", m_calc[:16])

    # Event hash chain
    evs = load_jsonl(root / "APEX_EVENTS.jsonl")
    prev = "0" * 64
    ev_ok = True
    for i, ev in enumerate(evs, start=1):
        integ = ev.get("integrity") or {}
        body = {k: v for k, v in ev.items() if k != "integrity"}
        if ev.get("seq") != i or integ.get("prev") != prev or integ.get("hash") != hashlib.sha256((prev + canon_str(body)).encode()).hexdigest():
            ev_ok = False
            break
        prev = integ["hash"]
    check(ev_ok and len(evs) > 0, "event_chain_valid", str(len(evs)))

    # Breakthrough integrity checks
    mg = load_json(root / "APEX_MULTIGEN_G0_G5.json")
    check(len(mg.get("generations", [])) == 6, "six_generations_G0_to_G5")
    check(mg.get("rollback_exact_verified") is True, "g3_rollback_exact")

    cr = load_json(root / "APEX_CODE_RSI.json")
    check(cr.get("ast_sandbox_all_blocked") is True, "code_rsi_ast_sandbox_blocked_all")
    check(cr.get("paid_cost_usd") == 0.0, "zero_paid_spend")

    imm = load_json(root / "APEX_ADVERSARIAL_IMMUNE.json")
    check(imm.get("all_blocked") is True and imm.get("total_vectors") == 10, "immune_10_of_10_blocked")

    gov = load_json(root / "APEX_GOVERNANCE_SUMMARY.json")
    check(gov.get("all_tests_pass") is True and gov.get("unauthorized_effects") == 0 and gov.get("post_kill_effects") == 0, "governance_zero_unauth_post_kill")

    reg = load_json(root / "APEX_UNIFIED_REGISTRY.json")
    check(len(reg.get("records", [])) >= 55 and reg.get("agi_status") == "NOT ESTABLISHED", "registry_preserves_all_history", str(len(reg.get("records", []))))

    passed = CHECKS - len(FAILURES)
    print(f"\n{passed}/{CHECKS} checks passed; {len(FAILURES)} failed")
    if FAILURES:
        print("FAILURES:", FAILURES)
        return 1
    return 0


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