# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fail-closed-when-an-a2a-warrant-chains-through-a-revoked-but-cached-signing-key.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fail-closed-when-an-a2a-warrant-chains-through-a-revoked-but-cached-signing-key.warrant.json
# Markdown SHA-256:   eb3b7485df8fa1c15d2a02960571900d0785c76ebe734e5a4a615c4f9e44cb85
# Code AST SHA-256:   58ce63d77c289b168975179ba448cd6447858af47f17614449830fea14289e9b
# Verified Classes:   WarrantFreshnessViolation, KeyRecord, RevManifest, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional


class WarrantFreshnessViolation(RuntimeError):
    """Raised when a warrant's validity window outlives the verifier's
    proof-of-freshness for the signing key, on an irreversible capability."""


@dataclass(frozen=True)
class KeyRecord:
    key_id: str
    key_epoch: int
    valid_from: datetime
    valid_until: datetime


@dataclass(frozen=True)
class RevManifest:
    epoch: int
    issued_at: datetime
    revoked_key_ids: frozenset
    head_key_id: str


@dataclass(frozen=True)
class Warrant:
    issuer_key_id: str
    issuer_key_epoch: int
    subject: str
    capability: str
    reversible: bool
    not_before: datetime
    not_after: datetime
    cosigned_by_head: bool


def verify_offline(
    w: Warrant,
    key: KeyRecord,
    manifest: RevManifest,
    now: datetime,
    delta_max: timedelta,
) -> str:
    if w.issuer_key_id != key.key_id or w.issuer_key_epoch != key.key_epoch:
        raise WarrantFreshnessViolation("warrant key/epoch does not match pinned key")

    if not (key.valid_from <= w.not_before and w.not_after <= key.valid_until):
        raise WarrantFreshnessViolation("warrant window escapes key validity interval")

    if key.key_id in manifest.revoked_key_ids:
        raise WarrantFreshnessViolation(f"key {key.key_id} revoked at epoch {manifest.epoch}")

    if w.issuer_key_epoch < manifest.epoch and not w.cosigned_by_head:
        raise WarrantFreshnessViolation(
            f"warrant superseded by epoch {manifest.epoch} without head co-signature"
        )

    freshness_horizon = manifest.issued_at + delta_max
    if w.not_after > freshness_horizon:
        if not w.reversible and not w.cosigned_by_head:
            gap = w.not_after - freshness_horizon
            raise WarrantFreshnessViolation(
                f"irreversible capability '{w.capability}' outlives freshness "
                f"horizon by {gap}; reject or require head co-signature"
            )
        return "accept_degraded_freshness"

    if now - manifest.issued_at > delta_max:
        return "accept_stale_manifest_bounded"

    return "accept"
