#!/usr/bin/env python3
"""Check a day's ledger: recompute the hash chain and each archived snapshot.
Usage: python3 verify_seal.py /path/to/winmora_seal 2026-10-22"""
import gzip, hashlib, json, sys
from pathlib import Path
root, date = Path(sys.argv[1]), sys.argv[2]
sha = lambda b: hashlib.sha256(b).hexdigest()
prev, bad, last = "0" * 64, 0, None
for l in (root / "ledger" / (date + ".jsonl")).read_text().splitlines():
    e = json.loads(l)
    if last and e["seq"] == last["seq"] and e["prev_hash"] == last["prev_hash"]:
        prev = last["prev_hash"]   # same seq sealed twice by overlapping runs
    blob = gzip.open(str(root / "archive" / date / e["archive"]), "rb").read()
    ok_state = sha(blob) == e["state_sha256"]
    ok_chain = e["prev_hash"] == prev and sha((prev + "|" + e["sealed_at_utc"] + "|" + e["kind"] + "|" + e["state_sha256"]).encode()) == e["entry_hash"]
    et = root / "archive" / date / (e["archive"][:-len(".json.gz")] + ".entry.txt")
    ok_entry = (not et.exists()) or sha(et.read_bytes()) == e["entry_hash"]
    print("seq %d %s  snapshot:%s chain:%s entry-file:%s" % (e["seq"], e["sealed_at_utc"], "OK" if ok_state else "BAD", "OK" if ok_chain else "BAD", ("OK" if ok_entry else "BAD") if et.exists() else "missing"))
    bad += (not ok_state) + (not ok_chain) + (not ok_entry); prev = e["entry_hash"]; last = e
print("ALL VALID" if not bad else "PROBLEMS FOUND"); sys.exit(1 if bad else 0)
