#!/usr/bin/env python3
# ═══════════════════════════════════════════════════════════════════════════
# ICA · INDEPENDENT EVIDENCE-PACKAGE VERIFIER (Tier 1 #13), Python edition.
#
# A SECOND implementation, in a different language and a different crypto stack
# (Python's `cryptography` / OpenSSL, not Node's), that verifies an
# ICA-EVIDENCE-PACKAGE-1 bundle byte-for-byte identically to the Node reference
# verifier (lib/ica-evidence-package.js). Two independent runtimes agreeing is
# what lets a customer, auditor, or court verify ICA WITHOUT trusting ICA's stack.
#
# It is offline and self-contained: the math runs on the public keys shipped
# INSIDE the bundle, and it never contacts ICA. WHO signed is proven only by
# pinning: with --trust-anchor (or --pubkeys) every bundled key's SHA-256
# fingerprint must be the key the pinned file holds under the same id, or the
# package is INVALID with reason KEY_NOT_PINNED. Pinning is REQUIRED by default:
# without a pin the result is UNPINNED and the verdict is INDETERMINATE (exit 3),
# never a pass (save https://ica.aleeth.com/.well-known/ica-trust-anchor.json once
# and confirm its fingerprints out of band). Pass --allow-unpinned to accept an
# unpinned run (it can then pass, with the UNPINNED caveat). A dimension whose input is absent is
# NOT_PROVIDED or INDETERMINATE, never a silent pass. Authority is resolved at the
# receipt's EVENT time, so a key revoked today does not invalidate old evidence.
# The post-quantum (ML-DSA) leg is checked with cryptography's ML-DSA when this build
# has it, and otherwise with mldsa_pure.py, a pure-Python FIPS 204 verify served beside
# this file (2026-11-25), so every Python 3 checks it. Only with neither is the leg
# NOT_VERIFIED_OFFLINE and the package INDETERMINATE, as the zero-dependency Node
# verifier reports it on a Node without ML-DSA.
#
#   usage:  python3 ica_verify.py <package.json> [--trust-anchor <file>] [--pubkeys <file>] [--allow-unpinned]
#   stdout: {"overall": "...", "dimensions": {...}, "key_pinning": {...}, "notes": [...]}
#   exit:   0 if overall is a VERIFIED_* / HISTORICALLY_VALID / PROVISIONAL pass,
#           2 if INVALID / INVALID_AT_EVENT_TIME (KEY_NOT_PINNED included),
#           3 if INDETERMINATE, 1 on error.
#
# Dependencies: Python 3 stdlib + `cryptography` (a widely-audited library, not
# ICA code). The canonicalization and verdict logic are implemented here from
# scratch, so this file itself is the auditable independent implementation.
# ═══════════════════════════════════════════════════════════════════════════
import sys, json, hashlib, base64, datetime, re

FORMAT = "ICA-EVIDENCE-PACKAGE-1"

# ---- canonicalization: byte-for-byte match to lib/issue-step-receipt canonicalize ----
# Rules: object keys sorted by UTF-16 code units; arrays keep order; strings escaped
# exactly as JS JSON.stringify (short escapes \b\t\n\f\r, \u00XX for other controls,
# non-ASCII left as UTF-8, no escaping of '/'); numbers as ECMAScript ToString.
_ESC = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r'}

def _json_string(s):
    out = ['"']
    for ch in s:
        if ch in _ESC:
            out.append(_ESC[ch])
        elif ord(ch) < 0x20:
            out.append('\\u%04x' % ord(ch))
        else:
            out.append(ch)
    out.append('"')
    return ''.join(out)

def _js_number(v):
    # Integers (and integral floats) print without a decimal point, like JSON.stringify.
    if isinstance(v, int):
        return str(v)
    if v != v or v in (float('inf'), float('-inf')):
        raise ValueError("non-finite number is not canonicalizable")
    if v == 0:
        return "0"  # JS prints -0 as "0"
    if float(v).is_integer() and abs(v) < 1e21:
        return str(int(v))
    r = repr(v)
    return r

def canonicalize(v):
    if v is None:
        return "null"
    if isinstance(v, bool):  # bool before int (bool is an int subclass in Python)
        return "true" if v else "false"
    if isinstance(v, (int, float)):
        return _js_number(v)
    if isinstance(v, str):
        return _json_string(v)
    if isinstance(v, list):
        return "[" + ",".join(canonicalize(x) for x in v) + "]"
    if isinstance(v, dict):
        keys = sorted(v.keys(), key=lambda k: k.encode("utf-16-be"))
        return "{" + ",".join(_json_string(k) + ":" + canonicalize(v[k]) for k in keys) + "}"
    raise ValueError("unserializable type %s" % type(v).__name__)

def sha256_hex(b):
    return hashlib.sha256(b).hexdigest()

# ---- merkle inclusion: byte-for-byte match to lib/ledger-merkle ----
# Domain-separated (RFC-6962-style): leaf = SHA256(0x00 || utf8(receipt_hash)),
# node = SHA256(0x01 || left || right), odd-node promotion. Proof steps are
# {"side": "left"|"right", "hash": <hex sibling>}.
def _leaf_hash(receipt_hash):
    return hashlib.sha256(b"\x00" + str(receipt_hash).encode("utf-8")).digest()

def _node_hash(l, r):
    return hashlib.sha256(b"\x01" + l + r).digest()

def verify_inclusion(receipt_hash, proof, root):
    acc = _leaf_hash(receipt_hash)
    for step in (proof or []):
        sib = bytes.fromhex(step["hash"])
        acc = _node_hash(sib, acc) if step.get("side") == "left" else _node_hash(acc, sib)
    return acc.hex() == str(root)

# ---- crypto verifies via `cryptography` ----
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.primitives.asymmetric import ec
try:
    from cryptography.hazmat.primitives.asymmetric import mldsa
except ImportError:
    mldsa = None  # this cryptography build has no ML-DSA: a present leg is reported, never passed
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from rfc3161 import verify_rfc3161
# ML-DSA in pure Python (mldsa_pure.py, served beside this file; 2026-11-25, car V4): used for any suite this cryptography
# build cannot check, so the post-quantum leg is checked on every Python 3, not only where cryptography has ML-DSA.
# ICA_VERIFY_PURE_MLDSA=1 uses it for every suite (how ICA's tests prove the two agree).
try:
    import mldsa_pure
except Exception:  # missing, or a damaged copy: the leg is then reported unchecked, never passed, and nothing crashes
    mldsa_pure = None

def _mldsa_class(algorithm):
    """The ML-DSA public key class for a suite: cryptography's when it has one, else the pure-Python one, else None."""
    name = {"ml-dsa-65": "MLDSA65PublicKey", "ml-dsa-87": "MLDSA87PublicKey"}.get(algorithm)
    if name is None:
        return None
    if mldsa is not None and os.environ.get("ICA_VERIFY_PURE_MLDSA") != "1":
        cls = getattr(mldsa, name, None)
        if cls is not None:
            return cls
    return getattr(mldsa_pure, name, None) if mldsa_pure is not None else None

def verify_ed25519(pem, message, sig_b64):
    try:
        pub = load_pem_public_key(pem.encode("utf-8"))
        pub.verify(base64.b64decode(sig_b64), message)
        return True
    except (InvalidSignature, Exception):
        return False

def verify_es256(pem, message, der_sig_b64):
    # ES256 = ECDSA over P-256 with SHA-256; cryptography applies SHA-256 itself.
    try:
        pub = load_pem_public_key(pem.encode("utf-8"))
        pub.verify(base64.b64decode(der_sig_b64), message, ec.ECDSA(hashes.SHA256()))
        return True
    except (InvalidSignature, Exception):
        return False

def _ms(t):
    if t is None:
        return None
    if isinstance(t, (int, float)):
        return t
    try:
        s = t.replace("Z", "+00:00") if isinstance(t, str) else t
        return datetime.datetime.fromisoformat(s).timestamp() * 1000.0
    except Exception:
        return None

# From this date the ML-DSA leg decides whether a receipt is valid (ICA's lib/pq-verdict-policy.js, the founder's
# decision of 2026-11-13): a receipt whose signed receipt_body.issued_at is on or after it, or whose body names no
# issued_at when this verifier's clock is past it, needs its own ML-DSA leg present and verifying.
ML_DSA_VERDICT_FROM = "2029-12-31T00:00:00.000Z"
ML_DSA_VERDICT_FROM_MS = _ms(ML_DSA_VERDICT_FROM)


# issued_at read strictly, by arithmetic, exactly as ICA's lib/pq-verdict-policy.js and verify.js read it: YYYY-MM-DDTHH:MM:SS,
# up to six fraction digits, then Z or +hh:mm / -hh:mm; anything else is no time (verifier/issued-at-parity.json). ASCII digits
# only: Python's \d would also match other scripts' digits, which JavaScript's does not.
_ISSUED_AT = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2})[T ]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,6}))?(Z|([+-])([0-9]{2})(?::?([0-9]{2}))?)")


def issued_at_ms(t):
    if isinstance(t, bool):
        return None  # JSON true/false is no time (verify.js: typeof boolean)
    if isinstance(t, (int, float)):
        try:
            f = float(t)  # an integer too large for a double is Infinity in JavaScript: no time there, so none here
        except OverflowError:
            return None
        return t if f == f and f not in (float("inf"), float("-inf")) else None
    if not isinstance(t, str):
        return None
    m = _ISSUED_AT.fullmatch(t)
    if not m:
        return None
    y, mo, d, h, mi, s = (int(x) for x in m.group(1, 2, 3, 4, 5, 6))
    if not 1 <= mo <= 12:
        return None
    leap = (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
    dim = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1]
    if y < 1 or d < 1 or d > dim or h > 23 or mi > 59 or s > 59:
        return None
    off = 0
    if m.group(8) != "Z":
        oh, om = int(m.group(10)), int(m.group(11) or 0)
        if oh > 23 or om > 59:
            return None
        off = (-1 if m.group(9) == "-" else 1) * (oh * 60 + om) * 60000
    ms = int((m.group(7) or "0").ljust(3, "0")[:3])
    days = (datetime.date(y, mo, d) - datetime.date(1970, 1, 1)).days
    return (days * 86400 + h * 3600 + mi * 60 + s) * 1000 + ms - off


def clock_ms(now_ms=None):
    """now_ms when it is a finite number, else this machine's clock (an unreadable value is never "no date")."""
    if isinstance(now_ms, (int, float)) and not isinstance(now_ms, bool):
        try:
            f = float(now_ms)
        except OverflowError:
            f = float("inf")
        if f == f and f not in (float("inf"), float("-inf")):
            return now_ms
    return datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000.0


def ml_dsa_decides(body, now_ms):
    sealed = issued_at_ms(body.get("issued_at") if isinstance(body, dict) else None)
    return (now_ms if sealed is None else sealed) >= ML_DSA_VERDICT_FROM_MS

VERIFIED = {"VERIFIED_EXTERNALLY_ANCHORED", "VERIFIED_INTERNAL_FINALITY", "PROVISIONAL", "HISTORICALLY_VALID_REVOKED_NOW", "VERIFIED_POST_QUANTUM"}
TRUST_ANCHOR_URL = "https://ica.aleeth.com/.well-known/ica-trust-anchor.json"
PQ_SUITES = ("ml-dsa-65", "ml-dsa-87")  # lib/receipt-signer.js SUITE_TABLE
# Raw public key length per suite (verify.js MLDSA_SUITES): a key of any other length
# is a failed leg before any capability question.
PQ_PUBLIC_KEY_BYTES = {"ml-dsa-65": 1952, "ml-dsa-87": 2592}
# Whole-string patterns, used with fullmatch: Python's `$` also matches before a
# trailing newline, which the JavaScript twins in verify.js do not.
_HEX64 = re.compile(r"[0-9a-f]{64}")
_B64 = re.compile(r"[A-Za-z0-9+/]+=*")

def _node_b64decode(s):
    """Bytes exactly as Node's Buffer.from(s, 'base64') reads them, the decoder the
    zero-dependency CLI (verify.js) uses: decoding stops at the first '=', the URL-safe
    '-' and '_' read as '+' and '/', any other character outside the alphabet
    (whitespace included) is skipped, and a lone trailing character is dropped. One
    decoder in both verifiers, so a key or signature never decodes to different bytes
    in Python than on the CLI (2026-10-19 review: a whitespace-wrapped ML-DSA key
    verified here and failed there, and an unpadded one did the reverse)."""
    if not isinstance(s, str):
        return b""
    core = s.split("=", 1)[0].replace("-", "+").replace("_", "/")
    core = re.sub(r"[^A-Za-z0-9+/]", "", core)
    if len(core) % 4 == 1:
        core = core[:-1]
    return base64.b64decode(core + "=" * (-len(core) % 4)) if core else b""

# ---- key pinning: the fingerprint /.well-known/ica-trust-anchor.json publishes ----
# SHA-256 over the key bytes in public_pem: the SPKI DER for an armored PEM, the
# raw key for the unarmored ML-DSA key (lib/key-fingerprint.js), plus one refusal:
# a PEM holding more than one block has no fingerprint. Same rule as verify.js.
def pin_fingerprint(public_pem):
    if not isinstance(public_pem, str):
        return None, None
    blocks = len(re.findall(r"-----BEGIN [A-Z ]+-----", public_pem))
    if blocks > 1:
        return None, None
    body = re.sub(r"\s+", "", re.sub(r"-----[A-Z ]+-----", "", public_pem))
    if not body or not _B64.fullmatch(body):
        return None, None
    raw = _node_b64decode(body)
    if not raw:
        return None, None
    return hashlib.sha256(raw).hexdigest(), ("spki_der" if blocks == 1 else "raw_public_key")

def _pq_public_key(algorithm, public_b64):
    """The raw ML-DSA public key, or None when it is malformed: verify.js mldsaVerify
    checks the alphabet on the whole string (no whitespace) and the length first."""
    if algorithm not in PQ_PUBLIC_KEY_BYTES or not isinstance(public_b64, str) or not _B64.fullmatch(public_b64):
        return None
    raw = _node_b64decode(public_b64)
    return raw if len(raw) == PQ_PUBLIC_KEY_BYTES[algorithm] else None

def parse_pins(doc, source, pins=None):
    """A trust anchor (ica-trust-anchor-v1) or a published key set; raises ValueError
    on a file that cannot be relied on (verify.js parsePins, same rules)."""
    if pins is None:
        pins = {"sources": [], "by_id": {}}
    keys = doc if isinstance(doc, list) else (doc.get("keys") if isinstance(doc, dict) else None)
    if not isinstance(keys, list):
        raise ValueError("%s: not a key set (no keys[] list)" % source)
    added = 0
    for k in keys:
        if not isinstance(k, dict):
            raise ValueError("%s: a keys[] entry is not an object" % source)
        kid = k.get("id") if isinstance(k.get("id"), str) and k.get("id") else (
            k.get("key_id") if isinstance(k.get("key_id"), str) and k.get("key_id") else None)
        if not kid:
            raise ValueError("%s: a keys[] entry has no id" % source)
        fp = None
        if k.get("public_pem") is not None:
            fp, _basis = pin_fingerprint(k.get("public_pem"))
            if not fp:
                raise ValueError("%s: key %s public_pem does not decode" % (source, kid))
        if k.get("fingerprint_sha256") is not None:
            stated = str(k.get("fingerprint_sha256")).lower()
            if not _HEX64.fullmatch(stated):
                raise ValueError("%s: key %s fingerprint_sha256 is not 64 hex characters" % (source, kid))
            if fp and fp != stated:
                raise ValueError("%s: key %s fingerprint_sha256 is not the fingerprint of its public_pem" % (source, kid))
            fp = stated
        if not fp:
            raise ValueError("%s: key %s carries neither public_pem nor fingerprint_sha256" % (source, kid))
        rev_raw = k.get("revoked_at") if k.get("revoked_at") is not None else k.get("retired_at")
        rev = None if rev_raw is None else _ms(rev_raw)
        if rev_raw is not None and rev is None:
            raise ValueError("%s: key %s revocation time %s does not parse" % (source, kid, json.dumps(rev_raw)))
        prev = pins["by_id"].get(kid)
        if prev and prev["fp"] != fp:
            raise ValueError("%s: key id %s is pinned to two different keys" % (source, kid))
        if prev and prev["revoked_at"] is not None:
            rev = prev["revoked_at"] if rev is None else min(prev["revoked_at"], rev)
        pins["by_id"][kid] = {"fp": fp, "revoked_at": rev}
        added += 1
    if not added:
        raise ValueError("%s: pins no key" % source)
    pins["sources"].append(source)
    return pins

def check_key_pins(keys, pins):
    rows = []
    keys = keys if isinstance(keys, dict) else {}
    for kid in sorted(keys.keys(), key=lambda x: x.encode("utf-16-be")):
        k = keys[kid] if isinstance(keys[kid], dict) else {}
        fp, basis = pin_fingerprint(k.get("public_pem"))
        row = {"id": kid, "algorithm": k.get("algorithm") or None, "fingerprint_sha256": fp,
               "fingerprint_basis": basis, "pinned": None}
        if pins is not None:
            p = pins["by_id"].get(kid)
            row["pinned"] = False
            if not fp:
                row["reason"] = "the bundled public key does not decode"
            elif p and p["fp"] == fp:
                row["pinned"] = True
            else:
                other = next((pid for pid, pv in pins["by_id"].items() if pv["fp"] == fp), None)
                if other:
                    row["reason"] = "the pinned file holds this key under id %s, not %s" % (other, kid)
                else:
                    row["reason"] = "not the key the pinned file holds for this id" if p else "this id is not in the pinned file"
        rows.append(row)
    if pins is None:
        status = "UNPINNED"
    elif not rows:
        status = "NO_BUNDLED_KEYS"
    else:
        status = "PINNED" if all(r["pinned"] is True for r in rows) else "KEY_NOT_PINNED"
    return {"status": status, "pinned_from": list(pins["sources"]) if pins is not None else None,
            "trust_anchor": TRUST_ANCHOR_URL, "keys": rows}

def _pq_leg_check(k, leg, message):
    """One ML-DSA leg over message: True, False, or None when this cryptography build cannot check the suite."""
    leg = leg if isinstance(leg, dict) else {}
    if not (isinstance(k, dict) and k.get("public_pem") and k.get("algorithm") in PQ_SUITES):
        return False
    raw_pk = _pq_public_key(k.get("algorithm"), k.get("public_pem"))
    if raw_pk is None:
        return False
    cls = _mldsa_class(k["algorithm"])
    if cls is None:
        return None
    sig = leg.get("signature")
    try:
        cls.from_public_bytes(raw_pk).verify(_node_b64decode("" if sig is None else str(sig)), message)
        return True
    except Exception:
        return False

def verify_package(pkg, pins=None, require_pin=False, after_break=False, now_ms=None):
    dims = {}
    notes = []
    if not isinstance(pkg, dict) or pkg.get("format") != FORMAT or "receipt" not in pkg:
        return {"overall": "INVALID", "dimensions": {}, "notes": ["not an %s" % FORMAT], "key_pinning": check_key_pins({}, pins)}
    r = pkg["receipt"]
    keys = pkg.get("keys") or {}
    key_pinning = check_key_pins(keys, pins)

    # 1. receipt integrity
    integrity_ok = False
    canonical = None
    try:
        canonical = canonicalize(r["receipt_body"]).encode("utf-8")
        integrity_ok = sha256_hex(canonical) == r["receipt_hash"]
        dims["receipt_integrity"] = "PASS" if integrity_ok else "FAIL"
        if not integrity_ok:
            notes.append("recomputed hash does not match receipt_hash")
    except Exception as e:
        dims["receipt_integrity"] = "FAIL"
        notes.append("canonicalize: %s" % e)

    # 2. primary Ed25519 signature
    primary_key = keys.get(r.get("signing_key_id"))
    primary_ok = False
    if not primary_key or not primary_key.get("public_pem"):
        dims["primary_signature"] = "INDETERMINATE"
        notes.append("no bundled public key for primary signer %s" % r.get("signing_key_id"))
    elif integrity_ok and r.get("signature"):
        primary_ok = verify_ed25519(primary_key["public_pem"], canonical, r["signature"])
        dims["primary_signature"] = "PASS" if primary_ok else "FAIL"
        if not primary_ok:
            notes.append("primary Ed25519 signature does not verify")
    else:
        dims["primary_signature"] = "FAIL"

    # 3. FIPS HSM ES256 co-signature(s)
    legs = r.get("kms_signatures") or []
    if not legs:
        dims["fips_hsm_cosignature"] = "NOT_PROVIDED"
    else:
        all_ok = True
        for leg in legs:
            k = keys.get(leg.get("key_id"))
            ok = bool(integrity_ok and k and k.get("public_pem") and k.get("algorithm") == "es256"
                      and verify_es256(k["public_pem"], canonical, leg.get("signature", "")))
            if not ok:
                all_ok = False
                notes.append("ES256 leg %s did not verify or key missing" % leg.get("key_id"))
        dims["fips_hsm_cosignature"] = "PASS" if all_ok else "FAIL"

    # 4. post-quantum leg (ML-DSA-65, FIPS 204): independently verified via cryptography's
    #    mldsa, over the same canonical bytes. The PQ public key rides in the bundle as
    #    base64 raw bytes (algorithm 'ml-dsa-65'), interoperable with the @noble signer.
    pq = r.get("pq_signatures") or []
    if not pq:
        dims["post_quantum_cosignature"] = "NOT_PROVIDED"
    else:
        failed = False
        unchecked = False
        _mldsa_cls = {a: _mldsa_class(a) for a in PQ_SUITES if _mldsa_class(a) is not None}
        for leg in pq:
            leg = leg if isinstance(leg, dict) else {}
            k = keys.get(leg.get("key_id"))
            raw_pk = _pq_public_key(k.get("algorithm"), k.get("public_pem")) if isinstance(k, dict) else None
            if not (integrity_ok and k and k.get("public_pem") and k.get("algorithm") in PQ_SUITES):
                ok = False
            elif raw_pk is None:
                ok = False  # a malformed key fails on every build, as on every Node (verify.js)
            elif k.get("algorithm") not in _mldsa_cls:
                ok = None  # this cryptography build cannot check this suite
            else:
                sig = leg.get("signature")
                try:
                    pub = _mldsa_cls[k["algorithm"]].from_public_bytes(raw_pk)
                    pub.verify(_node_b64decode("" if sig is None else str(sig)), canonical)
                    ok = True
                except Exception:
                    ok = False  # a key or signature that does not verify is a failed leg
            if ok is False:
                failed = True
                notes.append("ML-DSA leg %s did not verify or key missing" % leg.get("key_id"))
            elif ok is None:
                unchecked = True
        dims["post_quantum_cosignature"] = "FAIL" if failed else ("NOT_VERIFIED_OFFLINE" if unchecked else "PASS")
        if unchecked and not failed:
            notes.append("post-quantum ML-DSA leg present but this cryptography build has no ML-DSA, so it was not checked: put mldsa_pure.py (served beside this file) next to it, upgrade cryptography, or run the Node verifier on Node 24 or later")

    # 5. signer authority at EVENT time
    event_at = None
    for p in ("occurred_at", "issued_at"):
        v = _ms((r.get("receipt_body") or {}).get(p))
        if v is not None:
            event_at = v
            break
    auth_at_event = None
    revoked_now = False
    if not primary_key:
        auth_at_event = None
        notes.append("no bundled key metadata: event-time authority INDETERMINATE")
    elif event_at is None:
        auth_at_event = None
        notes.append("no occurred_at/issued_at on the body: event-time authority INDETERMINATE")
    else:
        nb = _ms(primary_key.get("not_before"))
        rev = _ms(primary_key.get("revoked_at"))
        # A pinned key's revocation comes from the pinned file too (verify.js, same rule).
        pin_row = next((k for k in key_pinning["keys"] if k["id"] == r.get("signing_key_id")), None)
        pinned_rev = pins["by_id"][r.get("signing_key_id")]["revoked_at"] if (pins is not None and pin_row and pin_row["pinned"] is True) else None
        if pinned_rev is not None and (rev is None or pinned_rev < rev):
            notes.append("the pinned file records signer %s as retired at %s; that time is used" % (r.get("signing_key_id"), pinned_rev))
            rev = pinned_rev
        after_start = (nb is None or event_at >= nb)
        revoked_before_event = (rev is not None and event_at >= rev)
        auth_at_event = after_start and not revoked_before_event
        revoked_now = rev is not None
    dims["signer_authorized_at_event_time"] = (
        "FAIL" if not primary_ok else
        "PASS" if auth_at_event is True else
        "FAIL" if auth_at_event is False else "INDETERMINATE")

    # 6. merkle inclusion (internal finality): the receipt is a leaf of the bundled root
    if pkg.get("inclusion_proof") and pkg.get("merkle_root"):
        try:
            inc = verify_inclusion(r["receipt_hash"], pkg["inclusion_proof"], pkg["merkle_root"])
        except Exception:
            inc = False
        dims["merkle_inclusion"] = "PASS" if inc else "FAIL"
        if not inc:
            notes.append("inclusion proof does not reconstruct the bundled merkle_root")
    else:
        dims["merkle_inclusion"] = "NOT_PROVIDED"
    # 7. external time anchor: an RFC 3161 TSA token stamping the SAME merkle_root.
    anchor = pkg.get("anchor")
    if anchor and anchor.get("tst_der_b64"):
        root_for_anchor = anchor.get("merkle_root") or pkg.get("merkle_root")
        try:
            av = verify_rfc3161(root_for_anchor, anchor["tst_der_b64"], anchor.get("trust_pem"))
        except Exception as e:
            av = {"valid": False}
            notes.append("anchor verify error: %s" % e)
        root_binds = bool(pkg.get("merkle_root") and root_for_anchor == pkg.get("merkle_root") and dims.get("merkle_inclusion") == "PASS")
        ok = av.get("valid") is True and av.get("chain_trusted") is True and root_binds
        dims["external_finality"] = "PASS" if ok else "FAIL"
        if av.get("gen_time"):
            notes.append("anchored at %s (TSA serial %s)" % (av.get("gen_time"), av.get("serial")))
    else:
        dims["external_finality"] = "NOT_PROVIDED"

    # 8. post-quantum path (mirrors lib/ica-evidence-package.js and tools/ica-verify/verify.js): PASS when the
    #    receipt's own ML-DSA leg verified, or when the bundled anchor_root (a ledger_merkle_root receipt)
    #    re-hashes, names the merkle_root the inclusion proof reconstructed, and every ML-DSA leg verifies.
    cos = dims.get("post_quantum_cosignature")
    pq_path = "PASS" if cos == "PASS" else ("NOT_VERIFIED_OFFLINE" if cos == "NOT_VERIFIED_OFFLINE" else "NOT_PROVIDED")
    ar = pkg.get("anchor_root")
    if isinstance(ar, dict):
        root_dim = "FAIL"
        try:
            rc = canonicalize(ar.get("receipt_body")).encode("utf-8")
            hash_ok = sha256_hex(rc) == ar.get("receipt_hash")
            body = ar.get("receipt_body") if isinstance(ar.get("receipt_body"), dict) else {}
            payload = body.get("payload") if isinstance(body.get("payload"), dict) else {}
            named = payload.get("merkle_root") if body.get("artifact_kind") == "ledger_merkle_root" else None
            binds = bool(pkg.get("merkle_root")) and named == pkg.get("merkle_root") and dims.get("merkle_inclusion") == "PASS"
            legs = ar.get("pq_signatures") if isinstance(ar.get("pq_signatures"), list) else []
            failed = not legs
            unchecked = False
            for leg in legs:
                leg = leg if isinstance(leg, dict) else {}
                ok = _pq_leg_check(keys.get(leg.get("key_id")), leg, rc) if hash_ok else False
                if ok is False:
                    failed = True
                    notes.append("anchor root ML-DSA leg %s did not verify or key missing" % leg.get("key_id"))
                elif ok is None:
                    unchecked = True
            if not hash_ok:
                notes.append("anchor root body does not hash to its receipt_hash")
            if not binds:
                notes.append("anchor root does not name the bundled merkle_root, or the inclusion proof did not pass")
            if not legs:
                notes.append("anchor root carries no post-quantum leg (anchored before the ML-DSA leg was armed)")
            if not hash_ok or not binds:
                root_dim = "FAIL"
            elif not legs:
                root_dim = "NOT_PROVIDED"
            elif failed:
                root_dim = "FAIL"
            elif unchecked:
                root_dim = "NOT_VERIFIED_OFFLINE"
            else:
                root_dim = "PASS"
        except Exception:
            root_dim = "FAIL"
            notes.append("anchor root could not be read")
        dims["anchor_root_post_quantum"] = root_dim
        if root_dim == "PASS":
            pq_path = "PASS"
        elif root_dim == "FAIL" and pq_path != "PASS":
            pq_path = "FAIL"
        elif root_dim == "NOT_VERIFIED_OFFLINE" and pq_path == "NOT_PROVIDED":
            pq_path = "NOT_VERIFIED_OFFLINE"
    dims["post_quantum_path"] = pq_path

    # 9. the ML-DSA verdict (mirrors lib/ica-evidence-package.js section 9): from ML_DSA_VERDICT_FROM the receipt's
    #    own ML-DSA leg decides, so it must be present and verify; a missing leg is INVALID.
    if ml_dsa_decides(r.get("receipt_body"), clock_ms(now_ms)):
        pqc = dims.get("post_quantum_cosignature")
        dims["ml_dsa_verdict"] = {"PASS": "PASS", "NOT_PROVIDED": "MISSING", "NOT_VERIFIED_OFFLINE": "NOT_VERIFIED_OFFLINE"}.get(pqc, "FAIL")
        if dims["ml_dsa_verdict"] == "MISSING":
            notes.append("sealed on or after %s (or names no sealing time): the ML-DSA leg decides validity, and it is missing" % ML_DSA_VERDICT_FROM[:10])

    # ---- overall (fail-closed, honest) ----
    if dims["receipt_integrity"] != "PASS" or dims.get("primary_signature") == "FAIL":
        overall = "INVALID"
    elif dims.get("primary_signature") == "INDETERMINATE":
        overall = "INDETERMINATE"
    elif dims.get("fips_hsm_cosignature") == "FAIL" or dims.get("post_quantum_cosignature") == "FAIL" or dims.get("merkle_inclusion") == "FAIL" or dims.get("anchor_root_post_quantum") == "FAIL" or dims.get("ml_dsa_verdict") == "MISSING":
        overall = "INVALID"
    elif auth_at_event is False:
        overall = "INVALID_AT_EVENT_TIME"
    elif auth_at_event is None:
        overall = "INDETERMINATE"
    elif dims.get("external_finality") == "PASS":
        overall = "HISTORICALLY_VALID_REVOKED_NOW" if revoked_now else "VERIFIED_EXTERNALLY_ANCHORED"
    elif dims.get("external_finality") == "FAIL":
        overall = "INDETERMINATE"  # an anchor was claimed but could not be proven: never a pass
    elif dims.get("merkle_inclusion") == "PASS":
        overall = "HISTORICALLY_VALID_REVOKED_NOW" if revoked_now else "VERIFIED_INTERNAL_FINALITY"
    else:
        overall = "HISTORICALLY_VALID_REVOKED_NOW" if revoked_now else "PROVISIONAL"
    # A present post-quantum leg nobody could check never lets a verdict pass.
    if overall in VERIFIED and dims.get("post_quantum_cosignature") == "NOT_VERIFIED_OFFLINE":
        overall = "INDETERMINATE"

    reason = None
    if key_pinning["status"] == "KEY_NOT_PINNED":
        overall = "INVALID"
        reason = "KEY_NOT_PINNED"
        for k in key_pinning["keys"]:
            if k["pinned"] is False:
                notes.append("KEY_NOT_PINNED: bundled key %s (sha256:%s): %s" % (k["id"], k["fingerprint_sha256"] or "undecodable", k.get("reason")))
    elif key_pinning["status"] == "UNPINNED" and require_pin and overall in VERIFIED:
        overall = "INDETERMINATE"
        reason = "UNPINNED"
        notes.append("a pin is required by default and none was given (pass --allow-unpinned to accept an unpinned run), so who signed this package is not established")

    if after_break:
        # AFTER THE BREAK: Ed25519, ES256 and the RFC 3161 token's signature are treated as forgeable and not
        # counted. Only hashes (integrity, inclusion) and ML-DSA count; bundled keys must still be pinned.
        classical = overall
        # A receipt whose own ML-DSA leg decides (section 9) and is missing is INVALID in this mode too.
        if key_pinning["status"] == "KEY_NOT_PINNED" or dims["receipt_integrity"] != "PASS" or dims.get("post_quantum_path") == "FAIL" or dims.get("post_quantum_cosignature") == "FAIL" or dims.get("merkle_inclusion") == "FAIL" or dims.get("ml_dsa_verdict") == "MISSING":
            ab = "INVALID"
        elif dims.get("post_quantum_path") == "NOT_VERIFIED_OFFLINE":
            ab = "INDETERMINATE"
        elif dims.get("post_quantum_path") == "PASS":
            ab = "INDETERMINATE" if (key_pinning["status"] == "UNPINNED" and require_pin) else "VERIFIED_POST_QUANTUM"
        else:
            ab = "NOT_PROVABLE_AFTER_BREAK"
        notes.append("after the break: Ed25519, ES256 and RFC 3161 signatures are treated as forgeable and not counted; only hashes and ML-DSA count")
        notes.append("verdict before the break: %s" % classical)
        out = {"overall": ab, "classical_overall": classical, "after_break": True, "dimensions": dims, "revoked_now": revoked_now, "event_at_ms": event_at, "notes": notes, "key_pinning": key_pinning}
        if reason:
            out["reason"] = reason
        return out
    out = {"overall": overall, "dimensions": dims, "revoked_now": revoked_now, "event_at_ms": event_at, "notes": notes, "key_pinning": key_pinning}
    if reason:
        out["reason"] = reason
    return out

USAGE = "usage: python3 ica_verify.py <package.json> [--trust-anchor <file>] [--pubkeys <file>] [--allow-unpinned] [--after-the-break]\n"

def main():
    args = sys.argv[1:]
    # Pinning is required by default: an unpinned package is INDETERMINATE (exit 3), never a pass.
    # --allow-unpinned restores the old opt-out; --require-pin is an accepted no-op (the old flag).
    files, anchor, pubkeys, require_pin = [], None, None, True
    i = 0
    after_break = False
    while i < len(args):
        a = args[i]
        if a in ("--trust-anchor", "--pubkeys"):
            if i + 1 >= len(args):
                sys.stderr.write(USAGE)
                sys.exit(1)
            if a == "--trust-anchor":
                anchor = args[i + 1]
            else:
                pubkeys = args[i + 1]
            i += 2
            continue
        if a == "--require-pin":
            require_pin = True
        elif a == "--after-the-break":
            after_break = True
        elif a == "--allow-unpinned":
            require_pin = False
        elif a.startswith("--"):
            sys.stderr.write("unknown option %s\n" % a + USAGE)
            sys.exit(1)
        else:
            files.append(a)
        i += 1
    if len(files) != 1:
        sys.stderr.write(USAGE)
        sys.exit(1)
    pins = None
    try:
        for src in (anchor, pubkeys):
            if src is None:
                continue
            if re.match(r"^https?://", src, re.I):
                raise ValueError("%s: pass a saved copy of the file; this verifier never contacts the network" % src)
            with open(src, "r", encoding="utf-8") as f:
                pins = parse_pins(json.load(f), src, pins)
    except (ValueError, OSError) as e:
        sys.stderr.write("error: pin file: %s\n" % e)
        sys.exit(1)
    with open(files[0], "r") as f:
        pkg = json.load(f)
    res = verify_package(pkg, pins=pins, require_pin=require_pin, after_break=after_break)
    print(json.dumps(res, sort_keys=True))
    if res["overall"] in VERIFIED:
        sys.exit(0)
    if res["overall"] == "INDETERMINATE":
        sys.exit(3)
    sys.exit(2)

if __name__ == "__main__":
    main()
