#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Anil Jangra
"""
Check a broker-desk evidence pack offline, with the independent verifier.

    python3 check_pack.py evidence-pack.json [--key signing-key.json]

Three checks, none of which contacts anyone:
  1. the note and its salt produce the digest the evidence log recorded;
  2. that digest's entry is in the evidence log's Merkle tree (v2 proof);
  3. the quote is in the quote ledger, linked to a signed head (v1 proof).
"""
import hashlib
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
# In the repository the verifier is in tools/python; in the published kit, kit/verifier.
sys.path[:0] = [os.path.join(HERE, "..", "..", "tools", "python"), os.path.join(HERE, "..", "verifier")]
import riskrouter_verify as v  # noqa: E402

pack = json.load(open(sys.argv[1]))
key = json.load(open(sys.argv[sys.argv.index("--key") + 1])) if "--key" in sys.argv else None
ok = True


def report(passed, line):
    global ok
    print(("OK    " if passed else "FAIL  ") + line)
    ok = ok and passed


dn = pack["demands_and_needs"]
digest = hashlib.sha256(bytes.fromhex(dn["salt_hex"]) + dn["note"].encode("utf-8")).hexdigest()
report(digest == pack["evidence_proof"]["entry"]["record_digest"], "the note and its salt produce the recorded digest")
r = v.verify_evidence_proof(pack["evidence_proof"])
report(r["intact"], "the note's digest is entry %s of the evidence log" % r.get("leaf_index") if r["intact"] else r["reason"])
if r.get("signer_key_id"):
    report(True, "the note's claim carries the broker's own signature (key %s, claimed at %s)" % (r["signer_key_id"], r["claimed_at"]))
r = v.verify_entry_proof(pack["quote_proof"])
report(r["intact"], "the quote is entry %s of the quote ledger, linked to its head" % r.get("index") if r["intact"] else r["reason"])
if key:
    s = v.verify_head_signature(pack["evidence_proof"]["head"], pack["evidence_proof"].get("signature"), key)
    report(s["ok"], "the evidence head is signed" if s["ok"] else s["reason"])
    s = v.verify_attestation_signature(pack["quote_proof"], key)
    report(s["ok"], "the quote ledger head is signed" if s["ok"] else s["reason"])
sys.exit(0 if ok else 1)
