# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-signing-with-a-rotated-out-key-after-aaif-revocation-propagation-lags-credential-cache-ttl.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-signing-with-a-rotated-out-key-after-aaif-revocation-propagation-lags-credential-cache-ttl.warrant.json
# Markdown SHA-256:   ba3f8d323acdc8e5bbcaceec9477e256db2c7ebb0e760329af4078edf601a1d3
# Code AST SHA-256:   9cd39ac456b3dd1bdd5e9fcd1bdf3cdce5a180e538f199b4c3879df4a9057d08
# Verified Classes:   RevocationViewStaleError, Warrant, RevocationView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class RevocationViewStaleError(RuntimeError):
    """Raised when a warrant cannot be validated because the verifier's
    revocation view is older than the negotiated max_staleness budget."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    signer_key_id: str
    issued_at: datetime
    expires_at: datetime
    freshness_proof_at: datetime | None  # issuer-signed "not revoked as of"


@dataclass
class RevocationView:
    last_refresh: datetime
    revoked_key_ids: frozenset[str]


def validate_presentation(
    warrant: Warrant,
    view: RevocationView,
    now: datetime,
    max_staleness: timedelta,
    privileged: bool,
) -> None:
    # Expiry is necessary but not sufficient.
    if now >= warrant.expires_at:
        raise RevocationViewStaleError(
            f"warrant {warrant.warrant_id} expired at {warrant.expires_at}"
        )

    if warrant.signer_key_id in view.revoked_key_ids:
        raise RevocationViewStaleError(
            f"signer key {warrant.signer_key_id} is revoked"
        )

    view_age = now - view.last_refresh
    if view_age > max_staleness:
        # Fail-closed for privileged operations; the stale view cannot
        # certify non-revocation within the negotiated budget.
        if privileged:
            raise RevocationViewStaleError(
                f"revocation view age {view_age} exceeds max_staleness "
                f"{max_staleness}; refusing privileged presentation of "
                f"warrant {warrant.warrant_id}"
            )
        # For read-only, fall through only if a freshness proof covers the gap.
        if warrant.freshness_proof_at is None or (
            now - warrant.freshness_proof_at > max_staleness
        ):
            raise RevocationViewStaleError(
                f"stale view and no freshness proof newer than "
                f"max_staleness for warrant {warrant.warrant_id}"
            )

    # Acceptance: signature valid, not revoked, and revocation view is
    # within the shared staleness budget (or freshness-proved).
    return None
