#!/usr/bin/env python3
"""
verify_ledger_standalone.py — check a downloaded ledger.json with nothing but Python 3.

  python3 verify_ledger_standalone.py ledger.json

Checks that every entry's entry_hash equals SHA-256 of its canonical JSON (all fields except
entry_hash), that each entry points at the previous entry's hash, and that latest_hash is the last
entry. This proves the ledger is internally consistent. For independent proof of WHEN it existed,
verify the RFC 3161 tokens that ship next to it (see DATASET_CARD.md). Record-level re-hashing needs
the raw evidence excerpts, which are kept in the full store and are not part of this download.
"""
import hashlib
import json
import sys


def canonical(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"))


def main(path: str) -> int:
    doc = json.load(open(path, encoding="utf-8"))
    entries, prev, bad = doc.get("entries", []), None, 0
    for i, e in enumerate(entries):
        core = {k: v for k, v in e.items() if k != "entry_hash"}
        if hashlib.sha256(canonical(core).encode()).hexdigest() != e.get("entry_hash"):
            print(f"entry {i}: hash mismatch"); bad += 1
        if prev is not None and e.get("prev_entry_hash") != prev:
            print(f"entry {i}: link to previous entry broken"); bad += 1
        prev = e.get("entry_hash")
    if entries and doc.get("latest_hash") != prev:
        print("latest_hash does not match the last entry"); bad += 1
    print(f"{len(entries)} entries checked: " + ("OK" if not bad else f"{bad} PROBLEM(S)"))
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "ledger.json"))
