#!/usr/bin/env python3
"""Offline DiskShield report and licence verifier.

Standalone single-file tool: verifies detached Ed25519 report signatures,
embedded commercial licence attestations, and optional vendor revocation lists.
Works with standard Python 3.9+ without mandatory third-party dependencies;
uses `cryptography` when installed for hardware-accelerated Ed25519.
"""

from __future__ import annotations

import argparse
import base64
import binascii
import hashlib
import json
import os
import re
import sys
import unicodedata
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
from uuid import UUID

# Optional fast C-accelerated Ed25519
try:
    from cryptography.exceptions import InvalidSignature as _CryptoInvalidSignature
    from cryptography.hazmat.primitives import serialization as _crypto_serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import (
        Ed25519PublicKey as _CryptoEd25519PublicKey,
    )
    _HAS_CRYPTOGRAPHY = True
except ImportError:
    _HAS_CRYPTOGRAPHY = False

# For parity testing: can be toggled to test pure-Python fallback even if cryptography is installed
_FORCE_PURE_PYTHON = False

# --- Protocol Constants ---
FORMAT = "diskshield-report-signature-v2"
SIGNING_PREFIX_REPORT = b"DiskShield report pair v2\0"
SIGNING_PREFIX_LICENSE = b"DiskShield commercial license v1\x00"
SIGNING_PREFIX_REVOCATION = b"DiskShield revocation list v1\x00"

MAX_REPORT_BYTES = 20 * 1024 * 1024
MAX_MANIFEST_BYTES = 32768
MAX_LICENSE_BYTES = 16384
MAX_REVOCATION_BYTES = 262144
MAX_REVOCATION_ENTRIES = 2048

# Report customisation limits; kept equal to the reference implementation and
# enforced by the shared test vectors.
FIELD_KEYS = ("letterhead", "job", "asset", "site", "notes")
MULTILINE_KEYS = ("letterhead", "notes")
TEXT_LIMITS = {"header": 100, "letterhead": 500, "job": 64, "asset": 64, "site": 100,
               "notes": 500}
NOTES_MAX_LINES = 5
_LOGO_HASH = re.compile(r"[0-9a-f]{64}\Z")
_UNREADABLE = "unreadable customization block"

VENDOR_KEY_ID = "vendor-2026-d50e6cdf"
VENDOR_KEY_SHA256 = "d50e6cdf1531d9716234333d155b6683026573a14cb8c4b24acad5e7ba71e66b"
VENDOR_PUBLIC_KEY_PEM = (
    "-----BEGIN PUBLIC KEY-----\n"
    "MCowBQYDK2VwAyEAhl+LZ7eZknFpLz778JxoEaYe4thhgHeDzrJqHiuCh4k=\n"
    "-----END PUBLIC KEY-----\n"
)
VENDOR_PUBLIC_KEY_RAW = b"\x86\x5f\x8b\x67\xb7\x99\x92\x71\x69\x2f\x3e\xfb\xf0\x9c\x68\x11\xa6\x1e\xe2\xd8\x61\x80\x77\x83\xce\xb2\x6a\x1e\x2b\x82\x87\x89"

# Pinned vendor keyring: key id -> (SHA-256 of the PEM text, PEM text). A key
# id is vendor-YYYY-<sha8> or vendor-online-YYYY-<sha8>, where <sha8> starts the
# fingerprint. Licences and revocation lists are checked with the key named by
# their key_id; every entry is checked against its fingerprint before use.
VENDOR_KEYRING = {
    VENDOR_KEY_ID: (VENDOR_KEY_SHA256, VENDOR_PUBLIC_KEY_PEM),
    "vendor-online-2026-15474d00": ("15474d0019b847e201c5281336586315f9b66fc85ae628c7c6e74059812b368f", "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA9GsjbC4IlHf48fx3jk7Ut3LSqV4Q1Pvy7tbt88m/lfQ=\n-----END PUBLIC KEY-----\n"),
}
_VENDOR_KEY_ID_FORM = re.compile(r"vendor-(?:online-)?[0-9]{4}-([0-9a-f]{8})\Z")

FEATURES = frozenset({"signed_reports", "custom_fields", "batch_report", "full_verify"})
MANIFEST_FIELDS = frozenset({
    "format", "algorithm", "key_id", "public_key", "license",
    "xml_sha256", "pdf_sha256", "signature"
})
LICENSE_DOCUMENT_FIELDS = frozenset({"payload", "signature", "key_id"})
LICENSE_PAYLOAD_FIELDS = frozenset({
    "schema", "product", "license_id", "customer", "edition", "issued_on",
    "valid_from", "expires_on", "updates_until", "features", "report_key_id"
})
REVOCATION_DOCUMENT_FIELDS = frozenset({"payload", "signature", "key_id"})
REVOCATION_PAYLOAD_FIELDS = frozenset({"schema", "issued_on", "next_update", "revoked"})
REVOCATION_ENTRY_FIELDS = frozenset({"license_id", "revoked_on"})

_HEX = re.compile(r"[0-9a-f]{64}\Z")
_KEY_ID = re.compile(r"sha256:[0-9a-f]{64}\Z")
_GENERIC_KEY_ID = re.compile(r"[A-Za-z0-9_-]{1,64}\Z")
_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}\Z")
_CREATED = re.compile(
    r"[0-9]{4}-[0-9]{2}-[0-9]{2}"
    r"(?:T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?"
    r"(?:Z|[+-][0-9]{2}:[0-9]{2})?)?\Z"
)
_WHITESPACE = b" \t\r\n"
_BIDI_CONTROLS = frozenset(map(ord, "\u061c\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069"))

# --- Pure Python Edwards25519 & RFC 8032 Arithmetic ---
_P = 2 ** 255 - 19
_D = -121665 * pow(121666, -1, _P) % _P
_L = 2 ** 252 + 27742317777372353535851937790883648493
_SQRT_M1 = pow(2, (_P - 1) // 4, _P)
_IDENTITY = (0, 1)
_BX = 15112221349535400772501151409588531511454012693041857206046113283949847762202
_BY = 46316835694926478169428394003475163141307993866256225615783033603165251855960
_B = (_BX, _BY)


def _decode_point(raw: bytes) -> tuple[int, int] | None:
    """Decompress curve point per RFC 8032."""
    if len(raw) != 32:
        return None
    number = int.from_bytes(raw, "little")
    sign = number >> 255
    y = (number & ((1 << 255) - 1)) % _P
    u = (y * y - 1) % _P
    v = (_D * y * y + 1) % _P
    x = u * pow(v, 3, _P) * pow(u * pow(v, 7, _P), (_P - 5) // 8, _P) % _P
    check = v * x * x % _P
    if check == (-u) % _P and check != u:
        x = x * _SQRT_M1 % _P
    elif check != u:
        return None
    if x & 1 != sign:
        x = (-x) % _P
    return x, y


def _point_add(a: tuple[int, int], b: tuple[int, int]) -> tuple[int, int]:
    (x1, y1), (x2, y2) = a, b
    t = _D * x1 * x2 * y1 * y2 % _P
    return (
        (x1 * y2 + y1 * x2) * pow(1 + t, -1, _P) % _P,
        (y1 * y2 + x1 * x2) * pow(1 - t, -1, _P) % _P,
    )


def _scalarmult(pt: tuple[int, int], e: int) -> tuple[int, int]:
    res = _IDENTITY
    base = pt
    while e > 0:
        if e & 1:
            res = _point_add(res, base)
        base = _point_add(base, base)
        e >>= 1
    return res


def is_weak_public_key(raw: bytes) -> bool:
    """True if raw bytes are not a curve point or [8]A is identity (order dividing 8)."""
    if type(raw) is not bytes or len(raw) != 32:
        return True
    point = _decode_point(raw)
    if point is None:
        return True
    for _ in range(3):
        point = _point_add(point, point)
    return point == _IDENTITY


def ed25519_verify_pure(pub_raw: bytes, sig_bytes: bytes, msg: bytes) -> bool:
    """RFC 8032 pure-Python Ed25519 signature verification."""
    if len(sig_bytes) != 64 or len(pub_raw) != 32:
        return False
    r_raw = sig_bytes[:32]
    s = int.from_bytes(sig_bytes[32:], "little")
    if s >= _L:
        return False
    a_point = _decode_point(pub_raw)
    if a_point is None:
        return False
    r_point = _decode_point(r_raw)
    if r_point is None:
        return False
    h = int.from_bytes(hashlib.sha512(r_raw + pub_raw + msg).digest(), "little") % _L
    return _scalarmult(_B, s) == _point_add(r_point, _scalarmult(a_point, h))


def ed25519_verify(pub_raw: bytes, sig_bytes: bytes, msg: bytes) -> bool:
    """Hybrid Ed25519 verification: cryptography library if available, else pure-Python."""
    if len(pub_raw) != 32 or len(sig_bytes) != 64:
        return False
    if _HAS_CRYPTOGRAPHY and not _FORCE_PURE_PYTHON:
        try:
            key = _CryptoEd25519PublicKey.from_public_bytes(pub_raw)
            key.verify(sig_bytes, msg)
            return True
        except _CryptoInvalidSignature:
            return False
        except Exception:
            return False
    return ed25519_verify_pure(pub_raw, sig_bytes, msg)


# --- Strict Base64, JSON & XML helpers ---
class _Rejected(Exception):
    """Internal exception for rejected manifest or inputs."""


class LicenseError(ValueError):
    """The licence cannot be trusted or is outside its validity period."""


class RevocationError(ValueError):
    """The revocation list cannot be trusted."""


class RevocationExpired(RevocationError):
    """The revocation list is genuine but past its next update date."""


def _unique_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]:
    result = {}
    for name, value in pairs:
        if name in result:
            raise ValueError(f"duplicate field: {name}")
        result[name] = value
    return result


def _reject_constant(_: str) -> object:
    raise ValueError("numeric constants (NaN/Infinity) are not permitted")


def parse_strict_json(data: bytes) -> dict:
    return json.loads(
        data.decode("utf-8"),
        object_pairs_hook=_unique_pairs,
        parse_constant=_reject_constant,
    )


def canonical_json_ascii(obj: dict) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")


def canonical_json_utf8(obj: dict) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")


def _strict_b64(text: str) -> bytes:
    """Decode standard padded base64 and ensure strict canonical encoding."""
    if not isinstance(text, str):
        raise _Rejected("invalid manifest fields")
    try:
        data = base64.b64decode(text.encode("ascii"), validate=True)
    except (ValueError, binascii.Error) as exc:
        raise _Rejected("invalid manifest fields") from exc
    if base64.b64encode(data).decode("ascii") != text:
        raise _Rejected("invalid manifest fields")
    return data


def key_id_of(pub_raw: bytes) -> str:
    return "sha256:" + hashlib.sha256(pub_raw).hexdigest()


def parse_spki_pem(pem_bytes: bytes) -> bytes:
    """Parse Ed25519 SubjectPublicKeyInfo PEM, returning 32 raw public bytes."""
    if _HAS_CRYPTOGRAPHY and not _FORCE_PURE_PYTHON:
        try:
            key = _crypto_serialization.load_pem_public_key(pem_bytes)
            if not isinstance(key, _CryptoEd25519PublicKey):
                raise ValueError("Expected an Ed25519 public key")
            raw = key.public_bytes(_crypto_serialization.Encoding.Raw, _crypto_serialization.PublicFormat.Raw)
            if is_weak_public_key(raw):
                raise ValueError("weak public key: small-order point")
            return raw
        except Exception as exc:
            raise ValueError(f"invalid public key PEM: {exc}") from exc

    # Pure Python PEM / DER parsing
    try:
        text = pem_bytes.decode("utf-8")
        lines = [line.strip() for line in text.splitlines() if line.strip() and not line.startswith("-----")]
        der = base64.b64decode("".join(lines))
    except Exception as exc:
        raise ValueError(f"invalid public key PEM: {exc}") from exc
    # Standard Ed25519 SPKI DER prefix: 302a300506032b6570032100 (12 bytes) + 32 raw bytes
    if len(der) != 44 or der[:12] != b"\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00":
        raise ValueError("Expected an Ed25519 SPKI public key")
    raw = der[12:]
    if is_weak_public_key(raw):
        raise ValueError("weak public key: small-order point")
    return raw


def pinned_vendor_keys() -> dict[str, bytes]:
    """Raw keys of the pinned keyring; ValueError if an entry fails its fingerprint."""
    keys: dict[str, bytes] = {}
    digests = set()
    for key_id, (digest, pem) in VENDOR_KEYRING.items():
        match = _VENDOR_KEY_ID_FORM.fullmatch(key_id)
        data = pem.encode("ascii")
        if (match is None or hashlib.sha256(data).hexdigest() != digest
                or match.group(1) != digest[:8] or digest in digests):
            raise ValueError(f"pinned vendor key {key_id} does not match its fingerprint")
        digests.add(digest)
        keys[key_id] = parse_spki_pem(data)
    if keys.get(VENDOR_KEY_ID) != VENDOR_PUBLIC_KEY_RAW:
        raise ValueError("pinned vendor key does not match its fingerprint")
    return keys


def _read_file_bounded(path: Path, limit: int) -> bytes:
    try:
        with open(path, "rb") as stream:
            data = stream.read(limit + 1)
    except Exception as exc:
        raise OSError(f"cannot read {path}: {exc}") from exc
    if len(data) > limit:
        raise ValueError(f"File too large: {path}")
    return data


def _unsafe_character(char: str) -> bool:
    code = ord(char)
    return (code < 32 or 0x7F <= code <= 0x9F or 0xD800 <= code <= 0xDFFF
            or code in (0x2028, 0x2029) or code in _BIDI_CONTROLS)


def _safe(text: str) -> str:
    return "".join("?" if _unsafe_character(char) else char for char in text)


# --- Report customisation ---
@dataclass(frozen=True)
class Customization:
    header: str
    logo_sha256: str | None
    fields: tuple[tuple[str, str], ...]


def normalize_name(text: str) -> str:
    """NFKC, lower case, whitespace collapsed: only to compare names for display."""
    return " ".join(unicodedata.normalize("NFKC", text).lower().split())


def xml_has_customization(xml: bytes) -> bool:
    """True when the report may carry a <customization> block; fails closed."""
    if len(xml) > MAX_REPORT_BYTES or b"\x00" in xml:
        return True
    try:
        text = xml.decode("utf-8", errors="strict")
    except ValueError:
        return True
    try:
        if "<!" in text:
            return b"customization" in xml
        root = ET.fromstring(text)
    except (ET.ParseError, RecursionError):
        return b"customization" in xml
    return any(isinstance(child.tag, str) and child.tag.rpartition("}")[2] == "customization"
               for child in root)


def _validate_text(key: str, value: str) -> str:
    multiline = key in MULTILINE_KEYS
    for char in value:
        if char == "\n" and multiline:
            continue
        if _unsafe_character(char):
            raise ValueError(f"{key} contains a forbidden character")
    text = value.strip(" ")
    if len(text) > TEXT_LIMITS[key]:
        raise ValueError(f"{key} is longer than {TEXT_LIMITS[key]} characters")
    if multiline and text.count("\n") + 1 > NOTES_MAX_LINES:
        raise ValueError(f"{key} has more than {NOTES_MAX_LINES} lines")
    return text


def _blank(text: str | None) -> bool:
    return text is None or not text.strip()


def _element_text(node: ET.Element, key: str, *, required: bool) -> str:
    if len(node) or (node.attrib and key != "field") or (
            key == "field" and set(node.attrib) != {"key"}):
        raise ValueError(f"unexpected content in {key}")
    value = _validate_text(key if key in TEXT_LIMITS else node.get("key", ""),
                           node.text or "")
    if required and not value:
        raise ValueError(f"{key} is empty")
    return value


def parse_customization(xml: bytes) -> Customization | None:
    """The strictly validated <customization> child of the root, or None if absent.

    Raises ValueError("<reason>") when the block is present but not valid.
    """
    if len(xml) > MAX_REPORT_BYTES or b"\x00" in xml:
        raise ValueError(_UNREADABLE)
    try:
        text = xml.decode("utf-8", errors="strict")
        if "<!" in text:
            raise ValueError(_UNREADABLE)
        root = ET.fromstring(text)
    except (ValueError, ET.ParseError, RecursionError) as exc:
        raise ValueError(_UNREADABLE) from exc
    blocks = []
    for child in root:
        if not isinstance(child.tag, str):
            raise ValueError(_UNREADABLE)
        if child.tag == "customization":
            blocks.append(child)
        elif child.tag.rpartition("}")[2] == "customization":
            raise ValueError(_UNREADABLE)
    if not blocks:
        return None
    if len(blocks) > 1:
        raise ValueError("customization block repeated")
    block = blocks[0]
    if block.attrib or not _blank(block.text) or any(not _blank(c.tail) for c in block):
        raise ValueError("unexpected content in customization")
    children = list(block)
    names = [child.tag for child in children]
    if names not in (["header"], ["header", "logo"], ["header", "fields"],
                     ["header", "logo", "fields"]):
        raise ValueError("unexpected or misordered customization children")
    header = _element_text(children[0], "header", required=True)
    logo = None
    fields: list[tuple[str, str]] = []
    for child in children[1:]:
        if child.tag == "logo":
            logo = child.get("sha256")
            if (set(child.attrib) != {"sha256"} or len(child) or not _blank(child.text)
                    or logo is None or _LOGO_HASH.fullmatch(logo) is None):
                raise ValueError("logo hash is not 64 lowercase hex digits")
        else:
            if child.attrib or not _blank(child.text) or not len(child):
                raise ValueError("unexpected content in fields")
            for item in child:
                if item.tag != "field" or not _blank(item.tail):
                    raise ValueError("unexpected content in fields")
                key = item.get("key")
                if key not in FIELD_KEYS:
                    raise ValueError("unknown field key")
                fields.append((key, _element_text(item, "field", required=True)))
    order = [FIELD_KEYS.index(key) for key, _ in fields]
    if order != sorted(set(order)):
        raise ValueError("duplicate or misordered field keys")
    return Customization(header, logo, tuple(fields))


def _report_created(xml: bytes) -> str | None:
    """The <created> text declared by signer, or None if invalid/unsafe."""
    if len(xml) > MAX_REPORT_BYTES:
        return None
    try:
        text = xml.decode("utf-8", errors="strict")
        if "<!" in text:
            return None
        root = ET.fromstring(text)
        nodes = root.findall("created")
        if len(nodes) != 1 or not nodes[0].text:
            return None
        created = nodes[0].text
        if _CREATED.fullmatch(created) is None:
            return None
        datetime.fromisoformat(created)
        return created
    except Exception:
        return None


# --- Data Models ---
@dataclass(frozen=True)
class ParsedLicense:
    license_id: str
    customer: str
    edition: str
    issued_on: date
    valid_from: date
    expires_on: date | None
    updates_until: date
    features: frozenset[str]
    key_id: str
    report_key_id: str | None

    def valid_on(self, day: date) -> bool:
        if type(day) is not date:
            raise LicenseError("Invalid date")
        return self.valid_from <= day and (self.expires_on is None or day <= self.expires_on)


@dataclass(frozen=True)
class ParsedManifest:
    key_id: str
    public_key_raw: bytes
    license_document: bytes
    xml_sha256: str
    pdf_sha256: str
    signature: bytes
    signed_payload: bytes


@dataclass(frozen=True)
class AttestationResult:
    signature_valid: bool
    attested: bool
    license_id: str | None
    customer: str | None
    edition: str | None
    report_key_id: str | None
    report_created: str | None
    license_valid_at_report_date: bool | None
    revoked: bool | None
    problems: tuple[str, ...]
    customization: Customization | None = None
    header_matches_licensee: bool | None = None


# --- Core Verifiers ---
def parse_and_check_license(
    document: bytes,
    vendor_keys: dict[str, bytes],
    today: date | None = None,
) -> ParsedLicense:
    if not isinstance(document, bytes) or len(document) > MAX_LICENSE_BYTES:
        raise LicenseError("Invalid licence size")
    try:
        value = parse_strict_json(document)
    except Exception as exc:
        raise LicenseError("Malformed licence") from exc
    if not isinstance(value, dict) or value.keys() != LICENSE_DOCUMENT_FIELDS:
        raise LicenseError("Invalid document fields")
    key_id = value["key_id"]
    if not isinstance(key_id, str) or _GENERIC_KEY_ID.fullmatch(key_id) is None or key_id not in vendor_keys:
        raise LicenseError("Unknown licence signer")
    vendor_pub_raw = vendor_keys[key_id]

    payload = value["payload"]
    if not isinstance(payload, dict) or payload.keys() != LICENSE_PAYLOAD_FIELDS:
        raise LicenseError("Invalid licence fields")
    if type(payload["schema"]) is not int or payload["schema"] != 1:
        raise LicenseError("Unsupported licence schema")
    if payload["product"] != "DiskShield":
        raise LicenseError("Wrong product")

    lic_id = payload["license_id"]
    if not isinstance(lic_id, str):
        raise LicenseError("Invalid licence ID")
    try:
        if str(UUID(lic_id)) != lic_id:
            raise ValueError()
    except ValueError as exc:
        raise LicenseError("Invalid licence ID") from exc

    customer = payload["customer"]
    if (not isinstance(customer, str) or not 1 <= len(customer) <= 200
            or not customer.strip() or any(_unsafe_character(c) for c in customer)):
        raise LicenseError("Invalid customer")

    edition = payload["edition"]
    if edition not in ("tecnico", "azienda"):
        raise LicenseError("Invalid edition")

    def _parse_d(d_val: object, err: str) -> date:
        if not isinstance(d_val, str) or _DATE.fullmatch(d_val) is None:
            raise LicenseError(err)
        try:
            return date.fromisoformat(d_val)
        except ValueError as exc:
            raise LicenseError(err) from exc

    issued_on = _parse_d(payload["issued_on"], "Invalid licence date")
    valid_from = _parse_d(payload["valid_from"], "Invalid licence date")
    expires_on = None if payload["expires_on"] is None else _parse_d(payload["expires_on"], "Invalid licence date")
    updates_until = _parse_d(payload["updates_until"], "Invalid licence date")

    if (edition == "azienda" and expires_on is None) or (expires_on is not None and expires_on < valid_from):
        raise LicenseError("Invalid expiry")
    if updates_until < max(issued_on, valid_from):
        raise LicenseError("Invalid update period")

    features = payload["features"]
    if (not isinstance(features, list) or any(not isinstance(f, str) or f not in FEATURES for f in features)
            or len(features) != len(set(features))):
        raise LicenseError("Invalid features")

    report_key_id = payload["report_key_id"]
    if "signed_reports" in features:
        if not isinstance(report_key_id, str) or _KEY_ID.fullmatch(report_key_id) is None:
            raise LicenseError("Invalid report key ID")
    elif report_key_id is not None:
        raise LicenseError("Invalid report key ID")

    sig_text = value["signature"]
    if not isinstance(sig_text, str):
        raise LicenseError("Invalid signature")
    try:
        signature = base64.b64decode(sig_text, validate=True)
    except Exception as exc:
        raise LicenseError("Invalid signature") from exc
    if len(signature) != 64 or base64.b64encode(signature).decode("ascii") != sig_text:
        raise LicenseError("Invalid signature")

    canonical_payload = canonical_json_utf8(payload)
    if not ed25519_verify(vendor_pub_raw, signature, SIGNING_PREFIX_LICENSE + canonical_payload):
        raise LicenseError("Invalid signature")

    parsed = ParsedLicense(
        license_id=lic_id,
        customer=customer,
        edition=edition,
        issued_on=issued_on,
        valid_from=valid_from,
        expires_on=expires_on,
        updates_until=updates_until,
        features=frozenset(features),
        key_id=key_id,
        report_key_id=report_key_id,
    )
    if today is not None and not parsed.valid_on(today):
        raise LicenseError("Licence not currently valid")
    return parsed


def parse_and_check_revocations(
    document: bytes,
    vendor_keys: dict[str, bytes],
    today: date,
) -> frozenset[str]:
    if not isinstance(document, bytes) or len(document) > MAX_REVOCATION_BYTES:
        raise RevocationError("Invalid revocation list size")
    try:
        value = parse_strict_json(document)
    except Exception as exc:
        raise RevocationError("Malformed revocation list") from exc
    if not isinstance(value, dict) or value.keys() != REVOCATION_DOCUMENT_FIELDS:
        raise RevocationError("Invalid document fields")
    key_id = value["key_id"]
    if not isinstance(key_id, str) or _GENERIC_KEY_ID.fullmatch(key_id) is None or key_id not in vendor_keys:
        raise RevocationError("Unknown revocation signer")
    vendor_pub_raw = vendor_keys[key_id]

    payload = value["payload"]
    if not isinstance(payload, dict) or payload.keys() != REVOCATION_PAYLOAD_FIELDS:
        raise RevocationError("Invalid revocation fields")
    if type(payload["schema"]) is not int or payload["schema"] != 1:
        raise RevocationError("Unsupported revocation schema")

    def _parse_rev_date(v: object) -> date:
        if not isinstance(v, str) or _DATE.fullmatch(v) is None:
            raise RevocationError("Invalid revocation date")
        try:
            return date.fromisoformat(v)
        except ValueError as exc:
            raise RevocationError("Invalid revocation date") from exc

    issued_on = _parse_rev_date(payload["issued_on"])
    next_update = _parse_rev_date(payload["next_update"])
    if next_update < issued_on:
        raise RevocationError("Invalid update period")

    entries = payload["revoked"]
    if not isinstance(entries, list) or len(entries) > MAX_REVOCATION_ENTRIES:
        raise RevocationError("Invalid revocation entries")
    identifiers: set[str] = set()
    for entry in entries:
        if not isinstance(entry, dict) or entry.keys() != REVOCATION_ENTRY_FIELDS:
            raise RevocationError("Invalid revocation entry")
        lic_id = entry["license_id"]
        if not isinstance(lic_id, str):
            raise RevocationError("Invalid licence ID")
        try:
            if str(UUID(lic_id)) != lic_id:
                raise ValueError()
        except ValueError as exc:
            raise RevocationError("Invalid licence ID") from exc
        _parse_rev_date(entry["revoked_on"])
        if lic_id in identifiers:
            raise RevocationError("Duplicate licence ID")
        identifiers.add(lic_id)

    sig_text = value["signature"]
    if not isinstance(sig_text, str):
        raise RevocationError("Invalid signature")
    try:
        signature = base64.b64decode(sig_text, validate=True)
    except Exception as exc:
        raise RevocationError("Invalid signature") from exc
    if len(signature) != 64 or base64.b64encode(signature).decode("ascii") != sig_text:
        raise RevocationError("Invalid signature")

    canonical_payload = canonical_json_utf8(payload)
    if not ed25519_verify(vendor_pub_raw, signature, SIGNING_PREFIX_REVOCATION + canonical_payload):
        raise RevocationError("Invalid signature")

    if issued_on > today + timedelta(days=1):
        raise RevocationError("Revocation list issued in the future")
    if today > next_update:
        raise RevocationExpired("Revocation list expired")
    return frozenset(identifiers)


def parse_manifest(manifest_bytes: bytes) -> ParsedManifest:
    if type(manifest_bytes) is not bytes:
        raise _Rejected("manifest is not valid JSON")
    if len(manifest_bytes) > MAX_MANIFEST_BYTES:
        raise _Rejected("manifest too large")
    manifest = manifest_bytes.strip(_WHITESPACE)
    try:
        obj = parse_strict_json(manifest)
    except Exception as exc:
        raise _Rejected("manifest is not valid JSON") from exc
    if not isinstance(obj, dict):
        raise _Rejected("invalid manifest fields")
    if "format" in obj and obj["format"] != FORMAT:
        raise _Rejected("unsupported manifest format: re-sign the report with a bound licence")
    if obj.keys() != MANIFEST_FIELDS or any(type(v) is not str for v in obj.values()):
        raise _Rejected("invalid manifest fields")
    if manifest != canonical_json_ascii(obj):
        raise _Rejected("manifest is not in canonical form")
    if (obj["algorithm"] != "Ed25519" or _KEY_ID.fullmatch(obj["key_id"]) is None
            or _HEX.fullmatch(obj["xml_sha256"]) is None
            or _HEX.fullmatch(obj["pdf_sha256"]) is None):
        raise _Rejected("invalid manifest fields")

    pub_raw = _strict_b64(obj["public_key"])
    if len(pub_raw) != 32:
        raise _Rejected("invalid public key")
    if key_id_of(pub_raw) != obj["key_id"]:
        raise _Rejected("key ID does not match the public key")
    if is_weak_public_key(pub_raw):
        raise _Rejected("weak public key")

    lic_bytes = _strict_b64(obj["license"])
    if not 0 < len(lic_bytes) <= MAX_LICENSE_BYTES:
        raise _Rejected("invalid manifest fields")

    signature = _strict_b64(obj["signature"])
    if len(signature) != 64:
        raise _Rejected("invalid manifest fields")

    unsigned = {k: v for k, v in obj.items() if k != "signature"}
    signed_payload = SIGNING_PREFIX_REPORT + canonical_json_ascii(unsigned)
    return ParsedManifest(
        key_id=obj["key_id"],
        public_key_raw=pub_raw,
        license_document=lic_bytes,
        xml_sha256=obj["xml_sha256"],
        pdf_sha256=obj["pdf_sha256"],
        signature=signature,
        signed_payload=signed_payload,
    )


def verify_attestation(
    xml: bytes,
    pdf: bytes,
    manifest: bytes,
    vendor_keys: dict[str, bytes],
    revoked_ids: frozenset[str] | None = None,
    trusted_raw_key: bytes | None = None,
) -> AttestationResult:
    state = {
        "signature_valid": False, "attested": False, "license_id": None,
        "customer": None, "edition": None, "report_key_id": None,
        "report_created": None, "license_valid_at_report_date": None,
        "revoked": None, "customization": None,
        "header_matches_licensee": None,
    }
    problems: list[str] = []

    def make_result() -> AttestationResult:
        return AttestationResult(**state, problems=tuple(problems))

    try:
        parsed = parse_manifest(manifest)
        if (type(xml) is not bytes or type(pdf) is not bytes or not xml or not pdf
                or hashlib.sha256(xml).hexdigest() != parsed.xml_sha256
                or hashlib.sha256(pdf).hexdigest() != parsed.pdf_sha256):
            raise _Rejected("report files do not match the manifest")
        if not ed25519_verify(parsed.public_key_raw, parsed.signature, parsed.signed_payload):
            raise _Rejected("invalid signature")
    except _Rejected as exc:
        problems.append(str(exc))
        return make_result()

    state["report_key_id"] = parsed.key_id

    # Check pin against independently trusted key
    def _pin_matches(p_list: list[str]) -> bool:
        if trusted_raw_key is None:
            return True
        if key_id_of(trusted_raw_key) != parsed.key_id:
            p_list.append("signing key does not match the trusted key")
            return False
        return True

    try:
        licence = parse_and_check_license(parsed.license_document, vendor_keys, today=None)
    except LicenseError as exc:
        state["signature_valid"] = _pin_matches(problems)
        problems.append(f"licence not valid: {exc}")
        return make_result()

    state.update(
        license_id=licence.license_id,
        customer=licence.customer,
        edition=licence.edition,
    )
    pin_problems: list[str] = []
    state["signature_valid"] = _pin_matches(pin_problems)

    if revoked_ids is not None:
        state["revoked"] = licence.license_id in revoked_ids
        if state["revoked"] and state["signature_valid"]:
            problems.append("licence withdrawn by the vendor")

    usable = True
    if "signed_reports" not in licence.features:
        problems.append("licence does not include signed reports")
        usable = False
    elif licence.report_key_id != parsed.key_id:
        problems.append("licence is not bound to the signing key")
        usable = False

    problems.extend(pin_problems)
    if not usable or not state["signature_valid"]:
        return make_result()

    custom = None
    blocked = False
    if xml_has_customization(xml):
        try:
            custom = parse_customization(xml)
            if custom is None:
                raise ValueError(_UNREADABLE)
        except ValueError as exc:
            problems.append(f"customization not valid: {exc}")
            custom_ok = False
        else:
            custom_ok = True
            if "custom_fields" not in licence.features:
                problems.append("report has custom fields but the licence "
                                "does not include them")
                custom_ok = False
        if not custom_ok:
            custom = None
            blocked = True

    created = _report_created(xml)
    if created is None:
        problems.append("report date unreadable")
        return make_result()

    state["report_created"] = created
    in_window = licence.valid_on(datetime.fromisoformat(created).date())
    state["license_valid_at_report_date"] = in_window
    if not in_window:
        problems.append("report date outside the licence validity (date declared by the signer)")

    state["attested"] = in_window and state["revoked"] is not True and not blocked
    if not blocked and custom is not None:
        state["customization"] = custom
        state["header_matches_licensee"] = (
            normalize_name(custom.header) == normalize_name(licence.customer))
    return make_result()


# --- CLI Verification Driver ---
def run_verify(
    xml_path: Path,
    pdf_path: Path,
    signature_path: Path,
    public_key_path: Path | None = None,
    revocations_path: Path | None = None,
    vendor_keys: dict[str, bytes] | None = None,
    today: date | None = None,
) -> int:
    if vendor_keys is None:
        vendor_keys = pinned_vendor_keys()
    if today is None:
        today = date.today()

    xml = _read_file_bounded(xml_path, MAX_REPORT_BYTES)
    pdf = _read_file_bounded(pdf_path, MAX_REPORT_BYTES)
    manifest = _read_file_bounded(signature_path, MAX_MANIFEST_BYTES)

    trusted_raw = None
    if public_key_path is not None:
        pem = _read_file_bounded(public_key_path, 16384)
        trusted_raw = parse_spki_pem(pem)

    revoked_ids = None
    revocation_status = "not checked"
    if revocations_path is not None:
        rev_bytes = _read_file_bounded(revocations_path, MAX_REVOCATION_BYTES)
        try:
            revoked_ids = parse_and_check_revocations(rev_bytes, vendor_keys, today)
            revocation_status = ""
        except RevocationExpired:
            revocation_status = "list expired"
        except RevocationError:
            revocation_status = "list invalid"

    result = verify_attestation(xml, pdf, manifest, vendor_keys, revoked_ids, trusted_raw)
    withdrawn = result.revoked is True
    usable = revoked_ids is not None or revocations_path is None
    exit_code = 0 if result.attested and not withdrawn and usable else 2

    if not result.signature_valid:
        print("INVALID")
        for problem in result.problems:
            print(f"Problem: {problem}")
        print(f"Revocation: {revocation_status or 'not checked'}")
        return 1

    if exit_code == 0:
        print("VALID")
        print(f"Attested: {result.customer} ({result.edition}), licence {result.license_id}")
        print(f"Key: {result.report_key_id}")
    else:
        print("NOT ATTESTED")
        print("Signature: valid (integrity only)")

    if result.license_id is not None:
        valid_on = {True: "yes", False: "no", None: "unknown"}[result.license_valid_at_report_date]
        print(f"Report date declared by signer: {result.report_created or 'unknown'}; licence valid on that date: {valid_on}")

    custom = result.customization
    if custom is not None:
        print(f"Declared header (not verified by the vendor): {_safe(custom.header)}")
        if result.header_matches_licensee is False:
            print("Notice: the declared header differs from the attested licensee. "
                  "DiskShield only verifies that the report was signed under a "
                  "licence issued to the attested licensee.")
        if custom.logo_sha256 is not None:
            print(f"Logo: declared by the signer, sha256 {custom.logo_sha256}; "
                  "visual match not verified")
        for key, value in custom.fields:
            print(f"Declared field {key}: {_safe(value.replace(chr(10), ' / '))}")

    for problem in result.problems:
        print(f"Problem: {problem}")
    if not usable:
        print("Problem: revocation list unusable")

    if revoked_ids is not None:
        if result.revoked is None:
            revocation_status = "not evaluated"
        else:
            revocation_status = "revoked" if result.revoked else "not revoked"
    print(f"Revocation: {revocation_status}")
    return exit_code


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="diskshield-verify",
        description="Verify DiskShield PDF/XML report pairs and licence attestations offline.",
    )
    parser.add_argument("--xml", type=Path, required=True, help="report XML file")
    parser.add_argument("--pdf", type=Path, required=True, help="report PDF file")
    parser.add_argument("--signature", type=Path, required=True, help="report signature manifest (.sig)")
    parser.add_argument("--public-key", type=Path, default=None, help="optional trusted Ed25519 public key (.pem)")
    parser.add_argument("--revocations", type=Path, default=None, help="vendor-signed revocation list (.json)")
    # Testing & audit options
    parser.add_argument("--vendor-public-key", type=Path, default=None, help=argparse.SUPPRESS)
    parser.add_argument("--vendor-key-id", type=str, default=VENDOR_KEY_ID, help=argparse.SUPPRESS)
    parser.add_argument("--today", type=str, default=None, help=argparse.SUPPRESS)

    try:
        args = parser.parse_args(argv)
        vendor_keys = pinned_vendor_keys()
        if args.vendor_public_key is not None:
            v_pem = _read_file_bounded(args.vendor_public_key, 16384)
            v_raw = parse_spki_pem(v_pem)
            vendor_keys = {args.vendor_key_id: v_raw}

        ref_today = date.today()
        if args.today:
            ref_today = date.fromisoformat(args.today)

        return run_verify(
            xml_path=args.xml,
            pdf_path=args.pdf,
            signature_path=args.signature,
            public_key_path=args.public_key,
            revocations_path=args.revocations,
            vendor_keys=vendor_keys,
            today=ref_today,
        )
    except KeyboardInterrupt:
        print("\ndiskshield-verify: cancelled", file=sys.stderr)
        return 1
    except Exception as error:
        print(f"diskshield-verify: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
