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

Zero CAIN imports, zero network access, zero privileged credentials.
Independently validates cryptographic integrity, Merkle root, Ed25519 signatures,
statistical non-zero-p integrity, 40 release gates, public-surface audit, and
canonical registry consistency across all 4 verification modes.

Note: Cryptographic integrity proves evidence has not changed relative to its manifest.
It does NOT prove scientific conclusions; 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 ""))

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

    man_doc = json.loads(mp.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")

    files_ok = all((bdir / rel).exists() and sha256_file(bdir / rel) == exp for rel, exp in man["files"].items())
    chk(files_ok, "all_manifest_file_hashes", f"count={len(man['files'])}")

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

    base = json.loads((bdir / "E139_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")

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

    snap_doc = json.loads((bdir / "RESULTS.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")
    chk(snap["total_evaluations"] >= 5000, "campaign_5000_plus_evals", f"evals={snap['total_evaluations']}")

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

    ev_rows = [json.loads(ln) for ln in (bdir / "E139_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)}")

    zero_hits = []
    for sf in (
        "GENERALIZATION_RESULTS.json", "CAUSAL_RESULTS.json", "RSI_LINEAGE.json",
        "COLLECTIVE_RESULTS.json", "SCIENTIFIC_DISCOVERY.json", "E139_TRANSFER.json",
        "E139_ABSTRACTIONS.json", "E139_CONTINUAL.json", "E139_METACOGNITION.json",
    ):
        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 & governance invariants
    gen = json.loads((bdir / "GENERALIZATION_RESULTS.json").read_text())
    chk(gen["total_evaluations"] == 800, "open_world_800_evals")
    cwm = json.loads((bdir / "CAUSAL_RESULTS.json").read_text())
    chk(cwm["total_worlds"] == 500, "causal_world_model_500_worlds")
    rsi = json.loads((bdir / "RSI_LINEAGE.json").read_text())
    chk(rsi["generations_attempted"] == 20 and rsi["all_rollbacks_exact"], "rsi_g20_and_exact_rollback")
    gov = json.loads((bdir / "GOVERNANCE_RESULTS.json").read_text())
    chk(gov["unauthorized_effects"] == 0 and gov["post_kill_effects"] == 0, "mcpgate_zero_unauth_zero_post_kill")
    chk(gov["memory_verification"]["all_10_memory_tests_passed"], "memory_10_of_10_tests")

    gates = json.loads((bdir / "E139_RELEASE_GATES.json").read_text())
    g24 = next((g for g in gates["gates"] if g["gate"] == 24), {})
    chk(gates["total"] == 40 and g24.get("status") == "BLOCKED", "40_release_gates_ext_bench_honestly_blocked")

    psa = json.loads((bdir / "PUBLIC_SURFACE_AUDIT.json").read_text())
    chk(psa["three_homepages_lead_with_organism"] is True, "three_homepages_lead_with_organism")
    chk(psa["public_discovery_folder_files_count"] == 17, "public_discovery_17_files")
    chk(psa["consistency_mismatches"] == 0, "zero_cross_surface_consistency_mismatches")

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

    chk(snap["rsi_taxonomy"]["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")
    chk(snap["key_results"]["external_reproductions"] == 0, "honest_zero_external_reproductions")
    chk(snap["key_results"]["external_benchmarks_completed"] == 0, "honest_zero_external_benchmarks")

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


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