#!/usr/bin/env python3
"""CAIN-42 EVOLUTION 138 — Standalone Zero-Dependency Offline Evidence Verifier.

Zero CAIN imports, zero network access, zero privileged credentials.
Independently validates:
  1. SHA256SUMS + MANIFEST.json integrity & Ed25519 signature
  2. Signed E138 baseline manifest & Ed25519 signature
  3. Frozen E138 preregistration SHA-256
  4. Raw experiment records JSONL + RFC 6962 binary Merkle root recomputation
  5. Signed E138 snapshot SHA-256 & Ed25519 signature
  6. Statistical integrity: ZERO exact `p_value == 0.0` anywhere in E138 reports!
  7. Generation ancestry DAG integrity (G0..G10 + exact rollbacks)
  8. 30-Gate Release Gate Registry (confirming external benchmarks honestly BLOCKED)
  9. Public registry consistency (preserving all >= 65 historical E125..E138 records)
 10. Honest entity/status invariants (FIRME AI CORPORATION, AGI NOT ESTABLISHED, RSI EXPERIMENTAL)

Note: Cryptographic integrity proves evidence has not changed relative to its manifest.
It does NOT prove scientific claims are true; keep cryptographic and scientific claims separate.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path
from typing import Any

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


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


def sha256_obj(obj: Any) -> str:
    return hashlib.sha256(canon_bytes(obj)).hexdigest()


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


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


def verify_ed25519(pub_hex: str, obj: Any, sig_hex: str) -> bool:
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_hex)).verify(bytes.fromhex(sig_hex), canon_bytes(obj))
        return True
    except Exception:
        return False


def find_zero_p(obj: Any, path: str = "") -> list[str]:
    hits: list[str] = []
    if isinstance(obj, dict):
        for k, v in obj.items():
            sub = f"{path}.{k}" if path else k
            if k in ("p_value", "sign_test_p") and isinstance(v, (int, float)) and float(v) == 0.0:
                hits.append(sub)
            else:
                hits.extend(find_zero_p(v, sub))
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            hits.extend(find_zero_p(v, f"{path}[{i}]"))
    return hits


def main() -> int:
    bdir = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parent
    passed = 0
    failed = 0

    def chk(cond: bool, name: str, detail: str = "") -> None:
        nonlocal passed, failed
        if cond:
            passed += 1
            print(f"PASS {name}" + (f" {detail}" if detail else ""))
        else:
            failed += 1
            print(f"FAIL {name}" + (f" {detail}" if detail else ""))

    manifest_path = bdir / "MANIFEST.json"
    chk(manifest_path.exists(), "manifest_exists")
    if not manifest_path.exists():
        print(f"\n{passed}/{passed+failed} checks passed; {failed} failed")
        return 1

    man_doc = json.loads(manifest_path.read_text())
    man = man_doc["manifest"]
    chk(verify_ed25519(man_doc["public_key_hex"], man, man_doc["signature_hex"]), "manifest_ed25519_sig")
    chk(man.get("entity") == "FIRME AI CORPORATION", "entity_exact_firme_ai_corp")
    chk(man.get("agi_status") == "NOT ESTABLISHED", "agi_status_not_established")
    chk(man.get("rsi_status") == "EXPERIMENTAL", "rsi_status_experimental")

    # Verify every file hash in MANIFEST
    files_ok = True
    for rel, expected in man["files"].items():
        fp = bdir / rel
        if not fp.exists() or sha256_file(fp) != expected:
            files_ok = False
            chk(False, f"file_hash:{rel}")
    chk(files_ok, "all_manifest_file_hashes", f"count={len(man['files'])}")

    # Verify SHA256SUMS
    sums_ok = True
    for ln in (bdir / "SHA256SUMS").read_text().splitlines():
        if not ln.strip():
            continue
        exp, rel = ln.split("  ", 1)
        fp = bdir / rel
        if not fp.exists() or sha256_file(fp) != exp:
            sums_ok = False
    chk(sums_ok, "sha256sums_verified")

    # Baseline manifest signature
    base = json.loads((bdir / "E138_BASELINE_MANIFEST.json").read_text())
    chk(sha256_obj(base["manifest"]) == base["manifest_sha256"], "baseline_sha256")
    chk(verify_ed25519(base["public_key_hex"], base["manifest"], base["signature_hex"]), "baseline_ed25519_sig")

    # Preregistration hash
    prereg = json.loads((bdir / "E138_PREREGISTRATION.json").read_text())
    p_copy = {k: v for k, v in prereg.items() if k != "preregistration_sha256"}
    chk(sha256_obj(p_copy) == prereg["preregistration_sha256"], "preregistration_sha256")

    # Signed snapshot + Merkle root recomputation from raw JSONL
    snap_doc = json.loads((bdir / "E138_SNAPSHOT.json").read_text())
    snap = snap_doc["snapshot"]
    chk(sha256_obj(snap) == snap_doc["snapshot_sha256"], "snapshot_sha256")
    chk(verify_ed25519(snap_doc["public_key_hex"], snap, snap_doc["signature_hex"]), "snapshot_ed25519_sig")
    chk(snap["preregistration_sha256"] == prereg["preregistration_sha256"], "snapshot_matches_prereg")

    raw_rows = [json.loads(ln) for ln in (bdir / "E138_RECORDS.jsonl").read_text().splitlines() if ln.strip()]
    row_hashes_ok = all(sha256_obj({k: v for k, v in r.items() if k != "record_sha256"}) == r["record_sha256"] for r in raw_rows)
    recomputed_merkle = merkle_root([r["record_sha256"] for r in raw_rows])
    chk(row_hashes_ok and len(raw_rows) >= 20, "raw_records_hashes", f"rows={len(raw_rows)}")
    chk(recomputed_merkle == snap["merkle_root"], "merkle_root_exact_match", recomputed_merkle[:16])

    # Event chain integrity
    ev_rows = [json.loads(ln) for ln in (bdir / "E138_EVENTS.jsonl").read_text().splitlines() if ln.strip()]
    prev = "0" * 64
    ev_ok = len(ev_rows) >= 10
    for idx, r in enumerate(ev_rows, start=1):
        integ = r.get("integrity") or {}
        body = {k: v for k, v in r.items() if k != "integrity"}
        exp_h = hashlib.sha256(prev.encode("utf-8") + canon_bytes(body)).hexdigest()
        if r.get("seq") != idx or integ.get("prev") != prev or integ.get("hash") != exp_h:
            ev_ok = False
            break
        prev = integ["hash"]
    chk(ev_ok, "event_chain_intact", f"events={len(ev_rows)}")

    # Statistical integrity: ZERO exact p=0.0 across ALL E138 statistical JSON artifacts!
    stat_files = [
        "E138_REPLICATION.json",
        "E138_GENERALIZATION.json",
        "E138_TRANSFER.json",
        "E138_CODE_RSI.json",
        "E138_CAUSAL_STRESS.json",
        "E138_MULTIGEN_G0_G10.json",
        "E138_ABSTRACTIONS.json",
        "E138_METACOGNITION.json",
        "E138_COLLECTIVE.json",
    ]
    zero_hits = []
    for sf in stat_files:
        zero_hits.extend(find_zero_p(json.loads((bdir / sf).read_text()), sf))
    chk(len(zero_hits) == 0, "no_exact_zero_p_values", f"violations={len(zero_hits)}")

    # Scientific sanity & honesty checks
    rep = json.loads((bdir / "E138_REPLICATION.json").read_text())
    chk(len(rep["zero_p_value_bugs_found_and_corrected"]) >= 5, "replication_corrected_apex_zero_p")
    chk(rep["breakthroughs"]["5_neuro_symbolic_and_immune"]["verdict"] == "PARTIAL", "replication_honestly_downgraded_budget_halted_b5")

    gen = json.loads((bdir / "E138_GENERALIZATION.json").read_text())
    chk(gen["total_sealed_tasks_per_agent"] == 600, "generalization_600_sealed_tasks")
    chk(gen["overall_rates"]["cain_unified_e138"] > gen["overall_rates"]["compute_matched"], "generalization_beats_compute_matched")

    tr = json.loads((bdir / "E138_TRANSFER.json").read_text())
    chk(tr["total_evaluations"] >= 400, "transfer_400_plus_evals")
    chk(len(tr["negative_transfer_detected"]) >= 1, "transfer_discloses_negative_transfer")

    cs = json.loads((bdir / "E138_CAUSAL_STRESS.json").read_text())
    chk(cs["total_worlds"] == 400 and len(cs["regimes_tested"]) == 10, "causal_stress_400_worlds_10_regimes")

    mg = json.loads((bdir / "E138_MULTIGEN_G0_G10.json").read_text())
    chk(mg["generations_reached"] == 10 and mg["all_rollbacks_exact"], "multigen_g0_g10_and_exact_rollback")

    cr = json.loads((bdir / "E138_CODE_RSI.json").read_text())
    chk(cr["n_tasks"] == 40 and cr["sandbox_security_16_vectors"]["all_blocked"], "code_rsi_40_tasks_16_sandbox_blocked")

    mc = json.loads((bdir / "E138_METACOGNITION.json").read_text())
    chk(mc["live_llm_comparison"]["budget_halted_calls"] == 0, "metacognition_zero_budget_halts")

    sf_doc = json.loads((bdir / "E138_SAFETY_GOVERNANCE.json").read_text())
    chk(sf_doc["unauthorized_effects"] == 0 and sf_doc["post_kill_effects"] == 0, "mcpgate_zero_unauth_zero_post_kill")
    chk(sf_doc["memory_verification"]["all_10_memory_tests_passed"], "memory_10_of_10_tests")

    gates = json.loads((bdir / "E138_RELEASE_GATES.json").read_text())
    g23 = next((g for g in gates["gates"] if g["gate"] == 23), {})
    chk(gates["total"] == 30 and g23.get("status") == "BLOCKED", "30_release_gates_ext_bench_honestly_blocked")

    repro = json.loads((bdir / "E138_REPRODUCTIONS.json").read_text())
    chk(repro["external_reproduction_count"] == 0, "honest_zero_external_reproductions")

    reg = json.loads((bdir / "E138_UNIFIED_REGISTRY.json").read_text())
    r_copy = {k: v for k, v in reg.items() if k != "registry_sha256"}
    chk(sha256_obj(r_copy) == reg["registry_sha256"] and reg["counts"]["records"] >= 65, "registry_hash_and_history_preserved", f"records={reg['counts']['records']}")

    chk(snap["rsi_taxonomy_classification"]["neural_weights_modified"] is False, "honest_zero_neural_weight_self_mod")
    chk(snap["resource_accounting"]["paid_api_spend_usd"] == 0.0, "zero_paid_api_spend")

    print(f"\n{passed}/{passed + failed} checks passed; {failed} failed")
    return 0 if failed == 0 else 1


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