#!/usr/bin/env python3
"""E238 standalone verifier (no CAIN imports). Checks the signed manifest, then runs the three bundled track verifiers:
c8_verify.py (model transfer; re-executes every model answer), c8_curriculum_verify.py (growing curriculum), and
e0_analyze.py (e0 model-knowledge verdicts recomputed from raw rows, compared with the bundled analysis).
Usage: python3 -I verify_e238_offline.py <bundle dir>"""
import hashlib, json, subprocess, sys
from pathlib import Path
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()
def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    while len(leaves) > 1:
        if len(leaves) % 2: leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0] if leaves else sha(b"")
def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else "."); C = []
    def ck(n, ok, d=""): C.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})
    man = json.loads((B / "E238_MANIFEST.json").read_text()); ck("status", man.get("status") == STATUS)
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon({k: v for k, v in man.items() if k != "signature"})); ck("manifest signature", True)
    except Exception as ex: ck("manifest signature", False, ex)
    files = man["files"]; ck("all files present", all((B / f).exists() for f in files))
    bad = [f for f, h in files.items() if (B / f).exists() and sha((B / f).read_bytes()) != h]; ck("file hashes", not bad, bad[:3])
    ck("merkle root", merkle([B / f for f in files]) == man["merkle_root"])
    present = {str(p.relative_to(B)) for p in B.rglob("*") if p.is_file() and "__pycache__" not in p.parts}
    extra = present - set(files) - {"E238_MANIFEST.json", "PUBLICATION.json", "E238_OMEGA_SEAL.json"}; ck("no unlisted files", not extra, sorted(extra)[:5])
    ck("no engine source or secrets", not any(p.endswith((".pem", ".key", ".db", ".env")) or Path(p).name in ("c8_model_transfer.py", "c8_curriculum.py", "proposer.py", "c8_model_transfer_run.py", "c8_curriculum_run.py") for p in present))
    for name, args in (("c8 model transfer", ["c8_verify.py", "."]), ("c8 curriculum", ["c8_curriculum_verify.py", "."])):
        r = subprocess.run([sys.executable, "-I", str(B / args[0]), str(B)], capture_output=True, text=True); last = (r.stdout.strip().splitlines() or [""])[0]
        ck(f"{name} verifier", r.returncode == 0, last)
    if (B / "e0/E238_E0_RESULTS.json").exists():
        r = subprocess.run([sys.executable, "-I", str(B / "verify_e238_e0_recompute.py"), str(B / "e0/E238_E0_RESULTS.json")], capture_output=True, text=True)
        try: ck("e0 verdicts recomputed = bundled analysis", r.returncode == 0 and json.loads(r.stdout) == json.loads((B / "e0/E238_E0_ANALYSIS.json").read_text()))
        except ValueError as ex: ck("e0 verdicts recomputed = bundled analysis", False, ex)
    else: ck("e0 track results present", False, "E238_E0_RESULTS.json missing")
    ok = all(c["ok"] for c in C)
    print(json.dumps({"checks": len(C), "passed": sum(c["ok"] for c in C), "ok": ok, "verification": "E238 bundle (c8 model transfer + c8 curriculum + e0 model knowledge)"}))
    for c in C:
        if not c["ok"]: print("FAIL", c["check"], c["detail"])
    return 0 if ok else 1
if __name__ == "__main__": sys.exit(main())
