#!/usr/bin/env python3
"""CAIN-42 external reviewer kit — verify a sealed bundle without importing CAIN code.

Usage: python3 -I verify_all.py <bundle-dir> [--tamper]
Checks: manifest Ed25519 signature, every declared file hash, the Merkle root, and the
bundle's own standalone verifier. --tamper appends one byte to the run report in a copy and
expects the bundle verifier to fail.
"""
import hashlib, json, shutil, subprocess, sys, tempfile
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

EX = {"MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json"}
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(ps):
    l = sorted(sha(p.read_bytes()) for p in ps)
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i+1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")
def check(bdir):
    B = Path(bdir); man = json.loads((B / "MANIFEST.json").read_text())
    pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]), canon({k: v for k, v in man.items() if k != "signature"}))
    files = [B / n for n in man["files"]]
    if any(not p.exists() for p in files): raise SystemExit("KIT FAIL: declared file missing")
    for n, h in man["files"].items():
        if sha((B / n).read_bytes()) != h: raise SystemExit(f"KIT FAIL: file hash {n}")
    if merkle(files) != man["merkle_root"]: raise SystemExit("KIT FAIL: merkle root")
    v = [p for p in B.glob("verify_*offline*.py")]
    if not v: raise SystemExit("KIT FAIL: no bundle verifier")
    r = subprocess.run([sys.executable, "-I", str(v[0]), str(B)], capture_output=True, text=True)
    if r.returncode != 0: raise SystemExit("KIT FAIL: bundle verifier: " + (r.stdout + r.stderr)[-400:])
    print("KIT OK:", B.name, "manifest signature, file hashes, Merkle, verifier", (r.stdout.strip().splitlines() or [""])[-1])
def tamper(bdir):
    B = Path(bdir)
    with tempfile.TemporaryDirectory() as t:
        W = Path(t) / "bundle"; shutil.copytree(B, W)
        reports = sorted(W.glob("*RUN_REPORT*.json"))
        if not reports: raise SystemExit("KIT FAIL: no run report to tamper")
        reports[0].write_bytes(reports[0].read_bytes() + b" ")
        v = [p for p in W.glob("verify_*offline*.py")]
        r = subprocess.run([sys.executable, "-I", str(v[0]), str(W)], capture_output=True, text=True)
        if r.returncode == 0: raise SystemExit("KIT FAIL: tampered bundle was accepted")
        print("TAMPER REJECTED:", reports[0].name)

if __name__ == "__main__":
    if len(sys.argv) < 2: raise SystemExit("usage: verify_all.py <bundle> [--tamper]")
    if "--tamper" in sys.argv: tamper(sys.argv[1])
    else: check(sys.argv[1])
