#!/usr/bin/env python3
"""Verify a review-room audit chain (events.jsonl): every line carries prev = the previous line's hash and
hash = sha256 of the line itself (JSON, sorted keys, without the "hash" field). Usage: python3 chain-verify.py events.jsonl"""
import hashlib, json, sys
prev = "0" * 64; n = 0
for raw in open(sys.argv[1], encoding="utf-8"):
    if not raw.strip():
        continue
    n += 1; d = json.loads(raw)
    if d.get("prev") != prev:
        sys.exit(f"line {n}: prev does not match the previous hash")
    body = {k: v for k, v in d.items() if k != "hash"}
    want = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
    if d.get("hash") != want:
        sys.exit(f"line {n}: hash does not match the line")
    prev = d["hash"]
print(f"ok: {n} lines, chain intact, last hash {prev}")
