#!/usr/bin/env python3
"""Standalone Zero-CAIN-Import Offline Verifier for CAIN-42 Evolution 180 (E180)."""
import base64, hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

REQUIRED = ["E180_PREREGISTRATION.json", "E180_COMPOUNDING_RESULTS.json", "E180_FRESH_SALT_REPLICATION.json", "E180_NEGATIVE_RESULTS.md", "E180_FINAL_REPORT.md", "E180_MANIFEST.sha256"]

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

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

def main() -> int:
    bdir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
    ok = True
    def chk(name, cond, detail):
        nonlocal ok
        print(f"[{'PASS' if cond else 'FAIL'}] {name}: {detail}")
        if not cond:
            ok = False

    missing = [f for f in REQUIRED if not (bdir / f).exists()]
    man_p = bdir / "E180_SIGNATURES/manifest.json"
    chk("required_artifacts", not missing and man_p.exists(), f"missing={missing}")
    if missing or not man_p.exists():
        print("OVERALL: FAIL"); return 1

    man = json.loads(man_p.read_text())
    files = man["files"]
    bad, leafs = [], []
    for rel in sorted(files):
        p = bdir / rel
        if not p.exists():
            bad.append(f"MISSING:{rel}"); continue
        h = sha256_bytes(p.read_bytes())
        if h != files[rel]:
            bad.append(f"HASH:{rel}")
        leafs.append(hashlib.sha256(b"\x00" + f"{rel}:{h}".encode()).hexdigest())
    chk("manifest_hashes", not bad, f"checked={len(files)} bad={bad}")

    sha_lines = [ln.strip() for ln in (bdir / "E180_MANIFEST.sha256").read_text().splitlines() if ln.strip()]
    sha_map = {ln.split(None, 1)[1]: ln.split(None, 1)[0] for ln in sha_lines if " " in ln}
    chk("manifest_sha256_parity", sha_map == files, f"lines={len(sha_map)}")

    recomp = merkle_root(leafs)
    chk("merkle_root", recomp == man["merkle_root"], f"recomp={recomp[:16]}")

    pub = serialization.load_pem_public_key(man["public_key_pem"].encode())
    assert isinstance(pub, Ed25519PublicKey)
    payload = json.dumps({k: man[k] for k in ("schema", "merkle_root", "file_count", "preregistration_sha256", "generated_at")}, sort_keys=True).encode()
    try:
        pub.verify(base64.b64decode(man["signature_b64"]), payload)
        sig_ok = True
    except Exception:
        sig_ok = False
    chk("ed25519_signature", sig_ok, f"fp={man['pubkey_fingerprint']}")

    pre = json.loads((bdir / "E180_PREREGISTRATION.json").read_text())
    pre_re = sha256_bytes(json.dumps({k: v for k, v in pre.items() if k != "preregistration_sha256"}, indent=2, sort_keys=True).encode())
    chk("preregistration_hash", pre_re == pre["preregistration_sha256"] == man["preregistration_sha256"], f"sha={pre_re[:16]}")

    res = json.loads((bdir / "E180_COMPOUNDING_RESULTS.json").read_text())
    ta = res["track_a_library_compounding"]
    ta_re = [sum(ta["raw_generation_vectors"][f"G{k}"]) for k in range(5)]
    ta_ok = (ta_re == [g["sealed_solved"] for g in ta["generations"]])
    tb = res["track_b_researcher_compounding"]
    tb_re = [round(sum(tb["raw_scores"][f"G{k}"]) / len(tb["raw_scores"][f"G{k}"]), 5) for k in range(5)]
    tb_ok = all(abs(a - b) < 1e-4 for a, b in zip(tb_re, tb["trend"]["generation_means"]))
    chk("independent_compounding_recomputation", ta_ok and tb_ok and res["governance"]["all_governance_passed"], f"ta={ta_re} tb={tb_re}")

    leaked_py = [p.name for p in bdir.rglob("*.py") if p.name != "E180_OFFLINE_VERIFIER.py"]
    leaked_pem = [p.name for p in bdir.rglob("*.pem") if p.name != "public_key.pem"]
    chk("black_box_zero_leaks", not (leaked_py or leaked_pem), f"py={leaked_py} pem={leaked_pem}")
    chk("honest_agi_rsi_status", pre["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"} and res["status"] == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"}, str(res["status"]))

    print("OVERALL:", "PASS" if ok else "FAIL")
    return 0 if ok else 1

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