import hashlib, json, sys, zipfile
FIELDS = ("seq", "ts", "tenant_id", "actor_type", "actor_id", "action", "object_id",
          "labels", "purpose", "decision", "reason", "policy_hash", "prev_hash")
OPTIONAL = ("engine_hash", "session_id")
rows = [json.loads(l) for l in zipfile.ZipFile(sys.argv[1]).read("audit/audit_events.jsonl").splitlines()]
prev = "0" * 64
for r in rows:
    f = {k: r[k] for k in FIELDS} | {k: r[k] for k in OPTIONAL if r.get(k) is not None}
    h = hashlib.sha256(json.dumps(f, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
    assert r["prev_hash"] == prev and r["row_hash"] == h, f"chain breaks at row {r['seq']}"
    prev = h
print(f"{len(rows)} rows chain correctly, head {prev[:16]}")
