"""Verify an exported approval ledger. Supply the trusted public PEM separately."""
import hashlib
import json
import sys
from pathlib import Path
from cryptography.hazmat.primitives.serialization import load_pem_public_key

def canonical(x):
    return json.dumps(x,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False).encode()
def verify(log,key):
    previous='0'*64
    for i,rec in enumerate(log['records'],1):
        content=rec['content']
        if content['project']!=log['project'] or content['seq']!=i or content['previous']!=previous:
            raise ValueError(f'Chain link mismatch at record {i}')
        previous=hashlib.sha256(canonical(content)).hexdigest()
        if previous!=rec['hash']:raise ValueError(f'Content mismatch at record {i}')
        key.verify(bytes.fromhex(rec['signature']),bytes.fromhex(previous))
    if log['head']!=dict(project=log['project'],count=len(log['records']),hash=previous):
        raise ValueError('Head mismatch: count or tail changed')
    key.verify(bytes.fromhex(log['seal']),canonical(log['head']))
    return previous
if __name__=='__main__':
    if len(sys.argv)!=3:sys.exit('Usage: python verify_approvals.py ledger.json trusted-public.pem (requires cryptography)')
    try:print('Verified',verify(json.loads(Path(sys.argv[1]).read_text()),load_pem_public_key(Path(sys.argv[2]).read_bytes())))
    except Exception as e:sys.exit('Verification failed: '+(str(e) or type(e).__name__))
