#!/usr/bin/env python3
"""Stdlib + cryptography. Checks hashes, signature, and recomputes the stress summary from the raw rows."""
import hashlib, json, sys
from pathlib import Path
D = Path(sys.argv[1]); C = []
def check(n, ok): C.append(bool(ok)); print(("PASS " if ok else "FAIL ") + n)
m = json.loads((D/"MANIFEST.json").read_text())
check("no_unlisted_files", {str(p.relative_to(D)) for p in D.rglob("*") if p.is_file()} - {"MANIFEST.json"} == set(m["files"]))
check("hashes", all((D/f).exists() and hashlib.sha256((D/f).read_bytes()).hexdigest() == h for f, h in m["files"].items()))
L = sorted(m["files"].values())
while len(L) > 1:
    if len(L) % 2: L.append(L[-1])
    L = [hashlib.sha256((L[i]+L[i+1]).encode()).hexdigest() for i in range(0, len(L), 2)]
check("merkle", L[0] == m["merkle_root"])
try:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(m["pubkey_ed25519"])).verify(bytes.fromhex(m["signature"]), json.dumps({k: v for k, v in m.items() if k != "signature"}, sort_keys=True, separators=(",", ":")).encode()); ok = True
except Exception: ok = False
check("signature", ok)
S = json.loads((D/"SUMMARY.json").read_text())["stress"]
for f in sorted((D/"stress").glob("*.jsonl")):
    R = [json.loads(l) for l in f.read_text().splitlines()]
    check("recompute_" + f.stem, S[f.stem] == {"runs": len(R), "runs_with_safety_violation": sum(bool(r.get("violations")) for r in R), "recovered": sum(bool(r.get("live")) for r in R), "accepted": sum(r["allow"] for r in R), "requests": sum(r["req"] for r in R)})
print(f"{sum(C)}/{len(C)} checks passed"); sys.exit(0 if all(C) else 1)
