#!/usr/bin/env python3
"""
VMARAS Standalone Evidence Packet Verifier — CLI Tool

Independently verifies a VMARAS Evidence Packet with nothing but this file,
the packet, and the VMARAS public key. No account, no network, no
dependencies (Python 3.8+ stdlib; uses the `cryptography` package for
faster Ed25519 if it happens to be installed).

What is checked (v2 packets, format "vmaras-evidence-packet-v2"):
  1. Every receipt hash is recomputed from the receipt's own fields:
       SHA-256("VMARAS-RECEIPT-v2\\n" + RFC 8785 JCS(receipt fields))
  2. Hash-chain linkage (prev_hash) and sequence continuity (no gaps)
  3. input_hash = SHA-256(payload_json)
  4. Ed25519 signature on every receipt hash
  5. Integrity Manifest: ordered hash list, chain head, RFC 6962 Merkle root
  6. Ed25519 packet signature over the whole packet
  7. Signing-time order
  8. Evidence-bound approvals (ALERT_ACKNOWLEDGED receipts): the approval
     digest is recomputed from receipts 0..N, the action, the policy and the
     approver; the server's Ed25519 approval signature is checked
  9. Passkey (WebAuthn) approval confirmations, when present: the approver's
     own signature over authenticatorData || SHA-256(clientDataJSON), with
     clientDataJSON.type == "webauthn.get", challenge == base64url(digest),
     rpIdHash == SHA-256(rp_id), UP and UV flags. ES256, EdDSA and RS256.
     This check needs no VMARAS key at all. Pin approvers' passkeys with
     --passkey-fingerprint <sha256 hex> (shown under My Account).
v1 (legacy) receipts are recomputed with the v1 rule; their HMAC seal can
only be checked with --hmac-key.

TRUST: public keys printed inside a packet are self-asserted. Pin the key
with --pubkey (base64) or --keys keys.json (saved from GET /verify/keys).
Without a pinned key, signatures are reported as "UNPINNED".

Usage:
    python verifier.py packet.json --keys keys.json
    python verifier.py packet.json --pubkey <base64-ed25519-public-key>
    python verifier.py packet.json --verbose
    python verifier.py packet.json --json
    python verifier.py packet.json --keys keys.json --rp-id vmaras.com --passkey-fingerprint <hex>

Patent Pending — MedNexLabs LLC
"""

import argparse
import base64
import hashlib
import hmac
import json
import math
from decimal import Decimal
import os
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

RECEIPT_V2_DOMAIN = "VMARAS-RECEIPT-v2\n"
PACKET_V2_DOMAIN = "VMARAS-PACKET-v2\n"
APPROVAL_DOMAIN = "VMARAS-APPROVAL-v2\n"
WEBAUTHN_FORMAT = "webauthn-assertion-v1"


# ── Primitives ───────────────────────────────────────────────


def sha256_hex(data: str) -> str:
    # Node's UTF-8 encoder turns a lone surrogate into U+FFFD; do the same so a
    # raw string with one hashes identically instead of crashing.
    if _has_lone_surrogate(data):
        data = "".join("\ufffd" if 0xD800 <= ord(c) <= 0xDFFF else c for c in data)
    return hashlib.sha256(data.encode("utf-8")).hexdigest()


def _has_lone_surrogate(s: str) -> bool:
    return any(0xD800 <= ord(c) <= 0xDFFF for c in s)


def _js_number(n: Any) -> str:
    """ECMAScript Number::toString (ECMA-262 §6.1.6.1.20), as RFC 8785 requires."""
    if isinstance(n, bool):
        raise TypeError("bool is not a number")
    if isinstance(n, int) and abs(n) <= 2 ** 53:
        return str(n)
    n = float(n)  # JSON numbers are IEEE doubles
    if not math.isfinite(n):
        return "null"  # same as JSON.stringify (the server does the same)
    if n == 0:
        return "0"
    sign = "-" if n < 0 else ""
    # repr() gives the shortest round-trip digits, like ECMAScript.
    t = Decimal(repr(abs(n))).normalize().as_tuple()
    digits = "".join(str(d) for d in t.digits)
    k = len(digits)
    e = t.exponent + k  # value = 0.digits × 10^e
    if k <= e <= 21:
        out = digits + "0" * (e - k)
    elif 0 < e <= 21:
        out = digits[:e] + "." + digits[e:]
    elif -6 < e <= 0:
        out = "0." + "0" * (-e) + digits
    else:
        exp = e - 1
        out = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + ("+" if exp >= 0 else "-") + str(abs(exp))
    return sign + out


def _js_string(s: str) -> str:
    """JSON.stringify for strings, including lone surrogates (escaped as \\udXXX)."""
    out = json.dumps(s, ensure_ascii=False)
    return "".join(f"\\u{ord(c):04x}" if 0xD800 <= ord(c) <= 0xDFFF else c for c in out)


def _utf16_key(s: str) -> List[int]:
    b = s.encode("utf-16-be")
    return [int.from_bytes(b[i:i + 2], "big") for i in range(0, len(b), 2)]


def canonicalize(v: Any) -> str:
    """RFC 8785 JSON Canonicalization Scheme."""
    if v is None:
        return "null"
    if v is True:
        return "true"
    if v is False:
        return "false"
    if isinstance(v, str):
        return _js_string(v)
    if isinstance(v, (int, float)):
        return _js_number(v)
    if isinstance(v, list):
        return "[" + ",".join(canonicalize(x) for x in v) + "]"
    if isinstance(v, dict):
        keys = sorted(v.keys(), key=_utf16_key)
        return "{" + ",".join(_js_string(k) + ":" + canonicalize(v[k]) for k in keys) + "}"
    raise TypeError(f"JCS: unsupported type {type(v).__name__}")


def merkle_rfc6962(hashes: List[str]) -> Optional[str]:
    if not hashes:
        return None

    def mth(leaves: List[bytes]) -> bytes:
        if len(leaves) == 1:
            return hashlib.sha256(b"\x00" + leaves[0]).digest()
        k = 1
        while k * 2 < len(leaves):
            k *= 2
        return hashlib.sha256(b"\x01" + mth(leaves[:k]) + mth(leaves[k:])).digest()

    return mth([bytes.fromhex(h) for h in hashes]).hex()


# ── Ed25519 verification (RFC 8032) ──────────────────────────

def _ed25519_verify_pure(pub: bytes, msg: bytes, sig: bytes) -> bool:
    """Reference RFC 8032 verification (slow but dependency-free)."""
    p = 2 ** 255 - 19
    L = 2 ** 252 + 27742317777372353535851937790883648493
    d = (-121665 * pow(121666, p - 2, p)) % p
    I = pow(2, (p - 1) // 4, p)

    def xrecover(y: int) -> Optional[int]:
        xx = (y * y - 1) * pow(d * y * y + 1, p - 2, p)
        x = pow(xx, (p + 3) // 8, p)
        if (x * x - xx) % p != 0:
            x = (x * I) % p
        if (x * x - xx) % p != 0:
            return None
        return x

    def add(P, Q):
        (X1, Y1, Z1, T1), (X2, Y2, Z2, T2) = P, Q
        A = (Y1 - X1) * (Y2 - X2) % p
        B = (Y1 + X1) * (Y2 + X2) % p
        C = T1 * 2 * d * T2 % p
        D = Z1 * 2 * Z2 % p
        E, F, G, H = B - A, D - C, D + C, B + A
        return (E * F % p, G * H % p, F * G % p, E * H % p)

    def mul(s: int, P):
        Q = (0, 1, 1, 0)
        while s > 0:
            if s & 1:
                Q = add(Q, P)
            P = add(P, P)
            s >>= 1
        return Q

    def decode(b: bytes):
        y = int.from_bytes(b, "little")
        sign = y >> 255
        y &= (1 << 255) - 1
        if y >= p:
            return None
        x = xrecover(y)
        if x is None or (x == 0 and sign):
            return None
        if (x & 1) != sign:
            x = p - x
        return (x, y, 1, x * y % p)

    def equal(P, Q) -> bool:
        return (P[0] * Q[2] - Q[0] * P[2]) % p == 0 and (P[1] * Q[2] - Q[1] * P[2]) % p == 0

    if len(pub) != 32 or len(sig) != 64:
        return False
    A = decode(pub)
    R = decode(sig[:32])
    S = int.from_bytes(sig[32:], "little")
    if A is None or R is None or S >= L:
        return False
    By = 4 * pow(5, p - 2, p) % p
    Bx = xrecover(By)
    if Bx & 1:  # the base point uses the even (positive) root
        Bx = p - Bx
    B = (Bx, By, 1, Bx * By % p)
    h = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % L
    return equal(mul(S, B), add(R, mul(h, A)))


def _pure() -> bool:
    return os.environ.get("VMARAS_VERIFIER_PURE") == "1"  # force the stdlib paths (used by tests)


def ed25519_verify_bytes(pub: bytes, msg: bytes, sig: bytes) -> bool:
    if _pure():
        return _ed25519_verify_pure(pub, msg, sig)
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey  # type: ignore
        try:
            Ed25519PublicKey.from_public_bytes(pub).verify(sig, msg)
            return True
        except Exception:
            return False
    except ImportError:
        return _ed25519_verify_pure(pub, msg, sig)


def ed25519_verify(pub_b64: str, msg: str, sig_b64: str) -> bool:
    try:
        pub = base64.b64decode(pub_b64)
        sig = base64.b64decode(sig_b64)
    except Exception:
        return False
    return ed25519_verify_bytes(pub, msg.encode("utf-8"), sig)


# ── ECDSA P-256 / RSA PKCS#1 v1.5 (for passkeys) ─────────────

_P256_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
_P256_A = _P256_P - 3
_P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
_P256_G = (0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
           0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5)
_P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B


def _ec_add(P, Q):
    if P is None:
        return Q
    if Q is None:
        return P
    p = _P256_P
    if P[0] == Q[0] and (P[1] + Q[1]) % p == 0:
        return None
    if P == Q:
        lam = (3 * P[0] * P[0] + _P256_A) * pow(2 * P[1], p - 2, p) % p
    else:
        lam = (Q[1] - P[1]) * pow(Q[0] - P[0], p - 2, p) % p
    x = (lam * lam - P[0] - Q[0]) % p
    return (x, (lam * (P[0] - x) - P[1]) % p)


def _ec_mul(k, P):
    R = None
    while k:
        if k & 1:
            R = _ec_add(R, P)
        P = _ec_add(P, P)
        k >>= 1
    return R


def _der_ecdsa_sig(sig: bytes):
    """Strict DER: SEQUENCE { INTEGER r, INTEGER s }, short-form lengths,
    minimal positive integers, nothing after the sequence (same as OpenSSL)."""
    if len(sig) < 8 or len(sig) > 72 or sig[0] != 0x30 or sig[1] >= 0x80 or sig[1] != len(sig) - 2:
        raise ValueError("not a strict DER ECDSA signature")
    i = 2
    out = []
    for _ in range(2):
        if i + 2 > len(sig) or sig[i] != 0x02:
            raise ValueError("bad DER integer tag")
        n = sig[i + 1]
        if n == 0 or n >= 0x80 or i + 2 + n > len(sig):
            raise ValueError("bad DER integer length")
        v = sig[i + 2:i + 2 + n]
        if v[0] & 0x80:
            raise ValueError("negative DER integer")
        if n > 1 and v[0] == 0 and not v[1] & 0x80:
            raise ValueError("non-minimal DER integer")
        out.append(int.from_bytes(v, "big"))
        i += 2 + n
    if i != len(sig):
        raise ValueError("trailing bytes after DER signature")
    return out[0], out[1]


def p256_verify(x: int, y: int, data: bytes, sig_der: bytes) -> bool:
    if not _pure():
        try:
            from cryptography.hazmat.primitives import hashes  # type: ignore
            from cryptography.hazmat.primitives.asymmetric import ec  # type: ignore
            key = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key()
            try:
                key.verify(sig_der, data, ec.ECDSA(hashes.SHA256()))
                return True
            except Exception:
                return False
        except ImportError:
            pass
    try:
        r, s = _der_ecdsa_sig(sig_der)
    except Exception:
        return False
    n, p = _P256_N, _P256_P
    if not (0 < r < n and 0 < s < n):
        return False
    if (y * y - (x * x * x + _P256_A * x + _P256_B)) % p != 0:
        return False  # public key not on the curve
    e = int.from_bytes(hashlib.sha256(data).digest(), "big")
    w = pow(s, n - 2, n)
    R = _ec_add(_ec_mul(e * w % n, _P256_G), _ec_mul(r * w % n, (x, y)))
    return R is not None and R[0] % n == r


_SHA256_DIGESTINFO = bytes.fromhex("3031300d060960864801650304020105000420")


def rsa_pkcs1_sha256_verify(n: int, e: int, data: bytes, sig: bytes) -> bool:
    k = (n.bit_length() + 7) // 8
    if len(sig) != k:
        return False
    em = pow(int.from_bytes(sig, "big"), e, n).to_bytes(k, "big")
    t = _SHA256_DIGESTINFO + hashlib.sha256(data).digest()
    expected = b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t
    return hmac.compare_digest(em, expected)


# ── WebAuthn assertion (approver passkey) ────────────────────

def b64u_decode(s: str) -> bytes:
    s = str(s or "")
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def b64u_encode(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).decode("ascii").rstrip("=")


def cbor_decode(buf: bytes) -> Any:
    """Minimal CBOR (RFC 8949) decoder: ints, byte/text strings, arrays, maps, simple values."""
    pos = 0

    def length(info: int) -> int:
        nonlocal pos
        if info < 24:
            return info
        size = {24: 1, 25: 2, 26: 4, 27: 8}.get(info)
        if size is None:
            raise ValueError("CBOR: indefinite length not supported")
        v = int.from_bytes(buf[pos:pos + size], "big")
        pos += size
        return v

    def item() -> Any:
        nonlocal pos
        if pos >= len(buf):
            raise ValueError("CBOR: truncated")
        ib = buf[pos]
        pos += 1
        major, info = ib >> 5, ib & 0x1F
        if major == 0:
            return length(info)
        if major == 1:
            return -1 - length(info)
        if major in (2, 3):
            n = length(info)
            v = buf[pos:pos + n]
            pos += n
            return bytes(v) if major == 2 else v.decode("utf-8")
        if major == 4:
            return [item() for _ in range(length(info))]
        if major == 5:
            m = {}
            for _ in range(length(info)):
                k = item()
                m[k] = item()
            return m
        if major == 7 and info in (20, 21, 22):
            return {20: False, 21: True, 22: None}[info]
        raise ValueError(f"CBOR: unsupported major type {major}")

    return item()


def _origin_ok(origin: str, rp_id: str) -> bool:
    from urllib.parse import urlparse
    try:
        u = urlparse(origin)
    except Exception:
        return False
    host = u.hostname or ""
    if not (host == rp_id or host.endswith("." + rp_id)):
        return False
    return u.scheme == "https" or (u.scheme == "http" and host == "localhost")


_ALG_KTY = {-7: 2, -8: 1, -257: 3}  # ES256 ↔ EC2, EdDSA ↔ OKP, RS256 ↔ RSA


def verify_webauthn_assertion(rec: dict, approval_digest: str, pinned_fingerprints: Optional[List[str]] = None,
                              expected_rp_id: Optional[str] = None) -> Optional[str]:
    """Returns None when the assertion verifies, otherwise the reason."""
    try:
        if not isinstance(rec, dict) or rec.get("format") != WEBAUTHN_FORMAT:
            return "not a VMARAS WebAuthn assertion record"
        cdj = b64u_decode(rec["client_data_json"])
        cd = json.loads(cdj.decode("utf-8"))
        if cd.get("type") != "webauthn.get":
            return "clientDataJSON.type is not webauthn.get"
        if cd.get("challenge") != b64u_encode(bytes.fromhex(approval_digest)):
            return "the passkey signed a different challenge than this approval digest"
        rp_id = expected_rp_id or rec.get("rp_id") or ""
        if rec.get("rp_id") != rp_id:
            return f"RP ID {rec.get('rp_id')} is not the expected {rp_id}"
        if not _origin_ok(cd.get("origin", ""), rp_id):
            return f"origin {cd.get('origin')} is not on {rp_id}"
        ad = b64u_decode(rec["authenticator_data"])
        if len(ad) < 37:
            return "authenticatorData too short"
        if ad[:32] != hashlib.sha256(rp_id.encode("utf-8")).digest():
            return "authenticatorData.rpIdHash does not match the RP ID"
        flags = ad[32]
        if not flags & 0x01:
            return "user presence (UP) flag not set"
        if not flags & 0x04:
            return "user verification (UV) flag not set"
        cose = b64u_decode(rec["public_key_cose"])
        fp = hashlib.sha256(cose).hexdigest()
        if rec.get("public_key_fingerprint") and rec["public_key_fingerprint"] != fp:
            return "public key fingerprint does not match the key"
        if pinned_fingerprints and fp not in pinned_fingerprints:
            return "passkey public key is not one of the pinned keys"
        key = cbor_decode(cose)
        rec_alg = rec.get("public_key_alg")
        if rec_alg is not None and key.get(3) is not None and int(rec_alg) != key.get(3):
            return f"algorithm mismatch: record says {rec_alg}, key says {key.get(3)}"
        alg = int(rec_alg if rec_alg is not None else key.get(3))
        if alg not in _ALG_KTY:
            return f"unsupported passkey algorithm {alg}"
        if key.get(1) != _ALG_KTY[alg]:
            return f"key type {key.get(1)} cannot be used with alg {alg}"
        signed = ad + hashlib.sha256(cdj).digest()
        sig = b64u_decode(rec["signature"])
        if alg == -7 and key.get(1) == 2 and key.get(-1) == 1:
            ok = p256_verify(int.from_bytes(key[-2], "big"), int.from_bytes(key[-3], "big"), signed, sig)
        elif alg == -8 and key.get(1) == 1 and key.get(-1) == 6:
            ok = ed25519_verify_bytes(key[-2], signed, sig)
        elif alg == -257 and key.get(1) == 3:
            ok = rsa_pkcs1_sha256_verify(int.from_bytes(key[-1], "big"), int.from_bytes(key[-2], "big"), signed, sig)
        else:
            return f"unsupported passkey algorithm {alg}"
        return None if ok else "passkey signature is invalid"
    except Exception as e:  # malformed record
        return f"assertion could not be checked: {e}"


# ── Receipt hashing ──────────────────────────────────────────

def v2_receipt_hash(r: Dict[str, Any]) -> str:
    body = {
        "v": 2,
        "tenant": str(r["tenant"]),
        "chain_id": r["chain_id"],
        "sequence": r["sequence"],
        "recall_id": str(r["recall_id"]),
        "action_type": r["action_type"],
        "actor_id": r["actor_id"],
        "role": r["role"],
        "entity_type": r.get("entity_type") or None,
        "entity_id": r.get("entity_id") or None,
        "payload": json.loads(r["payload_json"]),
        "description": r.get("description") or "",
        "input_hash": r.get("input_hash") or None,
        "output_hash": r.get("output_hash") or None,
        "prev_hash": r.get("prev_hash") or None,
        "signed_at": r["signed_at"],
    }
    return sha256_hex(RECEIPT_V2_DOMAIN + canonicalize(body))


def v1_receipt_hash(r: Dict[str, Any]) -> str:
    return sha256_hex(f"{r['recall_id']}|{r['action_type']}|{r['actor_id']}|{r['payload_json']}|{r.get('prev_hash') or ''}")


# ── Verification ─────────────────────────────────────────────


@dataclass
class VerificationResult:
    status: str = "PASS"
    checks: Dict[str, str] = field(default_factory=dict)
    issues: List[str] = field(default_factory=list)
    receipt_details: List[Dict[str, Any]] = field(default_factory=list)
    stats: Dict[str, Any] = field(default_factory=dict)


def _check(result: VerificationResult, name: str, ok: Optional[bool], na: str = "SKIPPED") -> None:
    result.checks[name] = na if ok is None else ("PASS" if ok else "FAIL")
    if ok is False:
        result.status = "FAIL"


def _receipt_payload(r: Dict[str, Any]) -> Dict[str, Any]:
    if r.get("payload_json") is not None:
        try:
            return json.loads(r["payload_json"])
        except Exception:
            return {}
    return r.get("payload_redacted") or {}


def verify_approvals(result: "VerificationResult", receipts: List[Dict[str, Any]], keyring: Dict[str, str],
                     passkey_pins: Optional[List[str]], rp_id: Optional[str] = None) -> None:
    """Checks 8 and 9: evidence-bound approvals and passkey confirmations."""
    approvals = passkeys = 0
    digest_ok = sig_ok = pk_ok = True
    unpinned_rp: set = set()
    by_seq = {r.get("sequence"): r for r in receipts}
    for r in receipts:
        if r.get("action_type") != "ALERT_ACKNOWLEDGED":
            continue
        md = (_receipt_payload(r).get("metadata") or {})
        if not md.get("approval_digest"):
            continue
        approvals += 1
        label = f"Approval in receipt #{r.get('sequence')}"
        upto = md.get("approval_upto_sequence")
        prior = [by_seq[i].get("receipt_hash") for i in range(upto + 1) if i in by_seq] if isinstance(upto, int) else []
        if not isinstance(upto, int) or len(prior) != upto + 1 or upto >= (r.get("sequence") or 0):
            digest_ok = False
            result.issues.append(f"{label}: approved evidence 0..{upto} is not in this packet")
            continue
        evidence_state = sha256_hex("|".join(prior))
        digest = sha256_hex(APPROVAL_DOMAIN + canonicalize({
            "evidence_state": evidence_state,
            "upto_sequence": upto,
            "proposed_action": md.get("approval_action"),
            "policy_context": md.get("approval_policy"),
            "approver_id": md.get("approver_id"),
        }))
        if digest != md.get("approval_digest") or (md.get("evidence_state_hash") and md["evidence_state_hash"] != evidence_state):
            digest_ok = False
            result.issues.append(f"{label}: approval digest does not match receipts 0..{upto}, action, policy and approver")
            continue
        pub = keyring.get(md.get("approval_key_id") or "")
        if not pub or not ed25519_verify(pub, APPROVAL_DOMAIN + digest, md.get("approval_signature") or ""):
            sig_ok = False
            result.issues.append(f"{label}: server approval signature invalid or key unknown")
        pk = md.get("approval_passkey")
        if pk:
            passkeys += 1
            if not rp_id:
                unpinned_rp.add(str(pk.get("rp_id")) if isinstance(pk, dict) else "?")
            why = verify_webauthn_assertion(pk, digest, passkey_pins, rp_id)
            if why:
                pk_ok = False
                result.issues.append(f"{label}: passkey confirmation FAILED: {why}")
    _check(result, "approval_digests", digest_ok if approvals else None, "NONE")
    _check(result, "approval_signatures", sig_ok if approvals else None, "NONE")
    _check(result, "approval_passkeys", pk_ok if passkeys else None, "NONE")
    result.stats["approvals"] = approvals
    result.stats["passkey_approvals"] = passkeys
    if passkeys:
        result.stats["passkey_trust"] = "PINNED" if passkey_pins else "UNPINNED (key taken from the receipt)"
        result.stats["rp_id"] = f"PINNED ({rp_id})" if rp_id else f"UNPINNED (taken from the receipt: {', '.join(sorted(unpinned_rp))})"
        if not rp_id:
            result.issues.append("WARNING: the passkey RP ID was taken from the receipt. Pin it with --rp-id (for example --rp-id vmaras.com) so an assertion made for another site cannot pass.")
        if not passkey_pins and pk_ok:
            result.issues.append("Passkey signatures were checked against the public key recorded in the receipt. Pin the approver's key with --passkey-fingerprint for an independent result.")


def verify_packet(packet: dict, pinned_keys: Optional[Dict[str, str]] = None,
                  hmac_key: Optional[str] = None, passkey_pins: Optional[List[str]] = None,
                  rp_id: Optional[str] = None) -> VerificationResult:
    result = VerificationResult()
    receipts = packet.get("receipts") or []
    manifest = packet.get("integrity_manifest") or {}
    embedded = {k["key_id"]: k["public_key_base64"] for k in manifest.get("public_keys", []) if "key_id" in k}
    keyring = pinned_keys if pinned_keys else embedded

    result.stats = {
        "format": packet.get("format", "legacy"),
        "packet_type": packet.get("packet_type", "N/A"),
        "packet_id": packet.get("packet_id", "N/A"),
        "chain_id": packet.get("chain_id", "N/A"),
        "receipt_count": len(receipts),
        "generated_at": packet.get("generated_at", "N/A"),
        "key_trust": "PINNED" if pinned_keys else "UNPINNED (key taken from packet)",
    }

    if packet.get("format") != "vmaras-evidence-packet-v2":
        result.status = "UNSUPPORTED"
        result.issues.append("Not a v2 Evidence Packet. Legacy packets did not include full receipts and cannot be verified offline.")
        return result
    if not receipts:
        result.status = "EMPTY"
        result.issues.append("No receipts found in packet")
        return result

    hash_ok = link_ok = seq_ok = input_ok = sig_ok = time_ok = True
    seen_v2 = False
    any_sig_checked = False
    redacted = 0
    prev_hash: Optional[str] = None
    prev_ts: Optional[str] = None

    for i, r in enumerate(receipts):
        d: Dict[str, Any] = {
            "sequence": r.get("sequence"), "version": r.get("v", 1), "action_type": r.get("action_type"),
            "actor_id": r.get("actor_id"), "receipt_hash": r.get("receipt_hash"),
            "prev_hash": r.get("prev_hash"), "signed_at": r.get("signed_at") or r.get("created_at"), "issues": [],
        }
        if r.get("sequence") != i:
            d["issues"].append(f"Sequence gap: expected {i}, found {r.get('sequence')}")
            seq_ok = False
        if (r.get("prev_hash") or None) != prev_hash:
            d["issues"].append("Chain break: prev_hash does not match the previous receipt")
            link_ok = False
        if r.get("v") == 2:
            seen_v2 = True
        elif seen_v2:
            d["issues"].append("Version downgrade: v1 receipt after v2 receipts")
            link_ok = False

        if r.get("payload_json") is None:
            redacted += 1
            d["issues_info"] = "payload redacted: hash not recomputed"
        else:
            try:
                expected = v2_receipt_hash(r) if r.get("v") == 2 else v1_receipt_hash(r)
                if expected != r.get("receipt_hash"):
                    d["issues"].append("Receipt hash does not match its contents (tampered)")
                    hash_ok = False
            except Exception as e:  # malformed receipt
                d["issues"].append(f"Receipt could not be hashed: {e}")
                hash_ok = False
            if r.get("v") == 2 and sha256_hex(r["payload_json"]) != r.get("input_hash"):
                d["issues"].append("input_hash does not match payload")
                input_ok = False

        if r.get("v") == 2:
            pub = keyring.get(r.get("key_id") or "")
            if not pub:
                d["issues"].append(f"Unknown signing key {r.get('key_id')}")
                sig_ok = False
            else:
                any_sig_checked = True
                if not ed25519_verify(pub, r.get("receipt_hash") or "", r.get("signature") or ""):
                    d["issues"].append("Ed25519 signature invalid")
                    sig_ok = False
        elif hmac_key and r.get("digital_signature"):
            any_sig_checked = True
            exp = hmac.new(hmac_key.encode(), (r.get("receipt_hash") or "").encode(), hashlib.sha256).hexdigest()
            if not hmac.compare_digest(exp, r["digital_signature"]):
                d["issues"].append("HMAC seal invalid")
                sig_ok = False

        ts = d["signed_at"]
        if prev_ts and ts and ts < prev_ts:
            d["issues"].append("Signing time out of order")
            time_ok = False
        prev_ts = ts or prev_ts
        prev_hash = r.get("receipt_hash")
        result.receipt_details.append(d)

    _check(result, "receipt_hashes_recomputed", hash_ok)
    if redacted:
        result.checks["receipt_hashes_recomputed"] += f" ({redacted} redacted, not recomputed)"
    _check(result, "chain_linkage", link_ok)
    _check(result, "sequence_continuity", seq_ok)
    _check(result, "input_hashes", input_ok)
    _check(result, "receipt_signatures", sig_ok if any_sig_checked or not sig_ok else None)
    _check(result, "signing_time_order", time_ok)

    hashes = [r.get("receipt_hash") for r in receipts]
    _check(result, "manifest_hash_list", manifest.get("receipt_hashes") == hashes)
    _check(result, "chain_head", manifest.get("chain_head") == hashes[-1])
    _check(result, "merkle_root_rfc6962", manifest.get("merkle_root") == merkle_rfc6962(hashes))

    verify_approvals(result, receipts, keyring, passkey_pins, rp_id)

    ps = packet.get("packet_signature") or {}
    if isinstance(ps, dict) and ps.get("signature"):
        body = {k: v for k, v in packet.items() if k != "packet_signature"}
        signed_hash = sha256_hex(PACKET_V2_DOMAIN + canonicalize(body))
        pub = keyring.get(ps.get("key_id") or "")
        ok = signed_hash == ps.get("signed_hash") and bool(pub) and ed25519_verify(pub, signed_hash, ps["signature"])
        _check(result, "packet_signature", ok)
        if not ok:
            result.issues.append("Packet signature invalid (packet altered after export, or unknown key)")
    else:
        _check(result, "packet_signature", False)
        result.issues.append("Packet is not signed")

    if not pinned_keys and result.status == "PASS":
        result.status = "PASS (UNPINNED KEY)"
        result.issues.append("Signatures were checked against the key printed in the packet. Pin the key with --keys or --pubkey for an independent result.")
    return result


# ── CLI Output ───────────────────────────────────────────────

GREEN, RED, YELLOW, CYAN, RESET, BOLD = "\033[92m", "\033[91m", "\033[93m", "\033[96m", "\033[0m", "\033[1m"


def print_results(r: VerificationResult, verbose: bool = False) -> None:
    color = GREEN if r.status == "PASS" else RED if r.status == "FAIL" else YELLOW
    print(f"\n{BOLD}{'=' * 60}{RESET}\n{BOLD}  VMARAS Evidence Packet Verification{RESET}\n{'=' * 60}")
    print(f"\n  Status: {color}{BOLD}{r.status}{RESET}\n")
    for k, v in r.stats.items():
        print(f"  {k.replace('_', ' ').title():.<30} {v}")
    print(f"\n{BOLD}  Integrity Checks:{RESET}")
    for k, v in r.checks.items():
        c = GREEN if v.startswith("PASS") else YELLOW if v.startswith("SKIP") else RED
        print(f"    [{c}{v}{RESET}] {k.replace('_', ' ').title()}")
    if r.issues:
        print(f"\n{YELLOW}{BOLD}  Notes:{RESET}")
        for issue in r.issues:
            print(f"    ! {issue}")
    if verbose:
        print(f"\n{BOLD}  Receipts ({len(r.receipt_details)}):{RESET}")
        for d in r.receipt_details:
            c = RED if d["issues"] else GREEN
            print(f"\n    [{c}{'FAIL' if d['issues'] else 'PASS'}{RESET}] #{d['sequence']} {CYAN}{d['action_type']}{RESET} (v{d['version']})")
            print(f"         Actor: {d['actor_id']}  Signed: {d['signed_at']}")
            print(f"         Hash:  {d['receipt_hash']}")
            for issue in d["issues"]:
                print(f"         {RED}! {issue}{RESET}")
    print(f"\n{'=' * 60}\n")


def load_keys(path: Optional[str], pubkey: Optional[str]) -> Optional[Dict[str, str]]:
    keys: Dict[str, str] = {}
    if path:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        for k in data.get("keys", []):
            keys[k["key_id"]] = k["public_key_base64"]
    if pubkey:
        raw = base64.b64decode(pubkey)
        key_id = "vmaras-ed25519-" + hashlib.sha256(raw).hexdigest()[:16]
        keys[key_id] = pubkey
    return keys or None


def main() -> None:
    ap = argparse.ArgumentParser(description="VMARAS Standalone Evidence Packet Verifier")
    ap.add_argument("packet", help="Path to evidence packet JSON file")
    ap.add_argument("--keys", help="keys.json saved from GET /verify/keys (pins the public key)")
    ap.add_argument("--pubkey", help="Ed25519 public key, base64 (pins the public key)")
    ap.add_argument("--hmac-key", help="Legacy HMAC key, only for v1 receipts")
    ap.add_argument("--passkey-fingerprint", action="append", default=[],
                    help="SHA-256 (hex) of an approver's passkey public key; repeat for several. Pins passkey approvals.")
    ap.add_argument("--rp-id", help="Expected WebAuthn RP ID for passkey approvals (e.g. vmaras.com). Without it the receipt's value is used, with a warning.")
    ap.add_argument("--verbose", "-v", action="store_true")
    ap.add_argument("--json", action="store_true", help="Output as JSON")
    args = ap.parse_args()

    try:
        with open(args.packet, "r", encoding="utf-8") as f:
            packet = json.load(f)
        pinned = load_keys(args.keys, args.pubkey)
    except (json.JSONDecodeError, FileNotFoundError, ValueError) as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(2)

    pins = [f.strip().lower() for f in args.passkey_fingerprint if f.strip()] or None
    result = verify_packet(packet, pinned, args.hmac_key, pins, (args.rp_id or "").strip() or None)
    if args.json:
        print(json.dumps({
            "status": result.status, "checks": result.checks, "stats": result.stats, "issues": result.issues,
            "failed_receipts": [d for d in result.receipt_details if d["issues"]],
        }, indent=2))
    else:
        print_results(result, args.verbose)
    sys.exit(0 if result.status == "PASS" else 1)


if __name__ == "__main__":
    main()
