#!/usr/bin/env python3
"""Verify the ZenFlare desk ledger on your own machine. Stdlib only.

    python desk-verify.py            # in a checkout of this repo

Each record's hash must equal sha256 of its canonical bytes, and each
record must carry the previous record's hash — so any edit, insertion or
deletion after publication breaks the replay below. The .ots files are
OpenTimestamps proofs of the segment heads (verify with the `ots` client).
"""
import glob
import hashlib
import json
import sys

ok, prev, n = True, "0" * 64, 0
for path in sorted(glob.glob("desk-ledger-*.jsonl")):
    for i, line in enumerate(open(path, encoding="utf-8"), 1):
        if not line.strip():
            continue
        r = json.loads(line)
        n += 1
        h = hashlib.sha256(r["canonical"].encode()).hexdigest()
        if h != r["record_hash"]:
            print(f"BROKEN {path}:{i} — canonical does not match record_hash")
            ok = False
        if r["prev_hash"] != prev:
            print(f"BROKEN {path}:{i} — chain link does not match")
            ok = False
        prev = r["record_hash"]
print(f"{'DESK LEDGER OK' if ok else 'DESK LEDGER BROKEN'} — "
      f"{n} records, head {prev[:16]}…")
sys.exit(0 if ok else 1)
