#!/usr/bin/env python3
"""E129 Unified AGI-RSI Standalone Offline Verifier.

Python standard library ONLY. Imports ZERO CAIN runtime code.
Verified across 4 required execution modes:
  1. Normal user
  2. Unprivileged identity (nobody)
  3. Read-only evidence copy
  4. Intentionally corrupted evidence copy (MUST fail with non-zero exit code)
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

VALID_GATE_STATUSES = {"PASS", "PARTIAL", "FAIL", "BLOCKED", "NOT_TESTED"}
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 chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    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"E129 unified offline verifier root={root}")

    man = load_json(root / "MANIFEST.json")
    check(man.get("evolution") == "E129", "manifest_evolution")
    check(man.get("entity") == "FIRME AI CORPORATION", "manifest_entity")
    check(man.get("agi_status") == "NOT ESTABLISHED", "manifest_agi_not_established")
    check(man.get("rsi_status") == "EXPERIMENTAL", "manifest_rsi_experimental")

    for entry in man["files"]:
        fp = root / entry["path"]
        ok = fp.exists() and sha256_file(fp) == entry["sha256"]
        check(ok, f"sha256:{entry['path']}", "" if ok else "MISMATCH")

    # Baseline manifest integrity
    base = load_json(root / "E129_BASELINE_MANIFEST.json")
    check(hashlib.sha256(canon_str(base["manifest"]).encode()).hexdigest() == base["manifest_sha256"], "baseline_manifest_digest")
    check(base["manifest"].get("baseline_all_passed") is True, "baseline_all_passed")

    # Preregistration
    prereg = load_json(root / "E129_PREREGISTRATION.json")
    check(prereg.get("status") == "FROZEN_BEFORE_CONFIRMATORY_RUNS", "preregistration_frozen")
    check(prereg["hardware_disclosure"]["weight_training_claimed"] is False, "no_fake_gpu_weight_training")

    # Raw 4-arm unification experiments & Merkle root
    exps = load_jsonl(root / "E129_UNIFIED_EXPERIMENTS.jsonl")
    check(len(exps) == 800, "unification_800_scored_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_800_record_sha256_valid")
    m_calc = merkle_root(leaves)
    snap_signed = load_json(root / "E129_UNIFIED_SNAPSHOT.json")
    snap = snap_signed["snapshot"]
    check(hashlib.sha256(canon_str(snap).encode()).hexdigest() == snap_signed["snapshot_sha256"], "signed_snapshot_digest")
    check(m_calc == snap.get("merkle_root") == man.get("merkle_root"), "merkle_root_match", m_calc[:16])

    # In-memory tamper self-test
    tamp = list(leaves)
    tamp[0] = "0" * 64 if tamp[0] != "0" * 64 else "f" * 64
    check(merkle_root(tamp) != m_calc, "tamper_detection_merkle_flip")

    # Event hash chain
    evs = load_jsonl(root / "E129_EVENTS.jsonl")
    prev = "0" * 64
    ev_ok = True
    for idx, 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") != idx 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)))

    # Multi-gen RSI ancestry & rollback
    mg = load_json(root / "E129_MULTI_GENERATION_RSI.json")
    arch = load_json(root / "E129_ARCHITECTURE_REGISTRY.json")
    cands = load_json(root / "E129_CANDIDATE_REGISTRY.json")
    check(len(arch.get("generations", [])) == 4, "four_generations_G0_to_G3")
    check(mg["rollback_verification"]["rollback_event"]["exact_restore"] is True, "candidate_rollback_exact_restore")
    check(any(c["status"] == "ROLLED_BACK" for c in cands["candidates"]), "rejected_candidate_preserved")

    # Unified memory 8-property verification
    mem_v = load_json(root / "E129_MEMORY_VERIFICATION.json")
    check(mem_v.get("all_8_tests_passed") is True, "unified_memory_all_8_properties")

    # Governance & kill switch
    gov = load_json(root / "E129_GOVERNANCE_SUMMARY.json")
    check(gov.get("all_tests_pass") is True, "governance_all_tests_pass")
    check(gov.get("unauthorized_effects") == 0 and gov.get("post_kill_effects") == 0, "zero_unauth_and_post_kill")
    check(gov.get("rsi_self_authorization_blocked") is True, "rsi_self_auth_blocked")

    # External benchmarks honestly BLOCKED
    ext = load_json(root / "E129_EXTERNAL_BENCHMARKS.json")
    check(ext.get("overall_status") == "BLOCKED" and len(ext.get("adapters", [])) == 6, "external_benchmarks_honestly_blocked")

    # Unified registry preserves E125-E128 + E129
    reg = load_json(root / "E129_UNIFIED_REGISTRY.json")
    check(reg.get("agi_status") == "NOT ESTABLISHED" and len(reg.get("records", [])) >= 50, "unified_registry_50_plus_records", str(len(reg.get("records", []))))
    check(any(r["scientific_status"] == "FAIL" for r in reg["records"]), "registry_preserves_failures")

    # 30 Release Gates
    sc = load_json(root / "E129_SCORECARD.json")
    gates = sc.get("gates", [])
    check(len(gates) == 30, "release_gates_30", str(len(gates)))
    check(all(g.get("status") in VALID_GATE_STATUSES for g in gates), "release_gates_valid_statuses")

    # Three-site homepage snapshots
    for fn in ("clawx.html", "studio.html", "mcpgate.html"):
        hp = root / "homepages" / fn
        txt = hp.read_text(encoding="utf-8", errors="replace") if hp.exists() else ""
        check(hp.exists() and "E129-UNIFIED-" in txt and "NOT ESTABLISHED" in txt, f"homepage_snapshot:{fn}")

    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())
