# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-verifiable-credential-as-revoked-before-the-revocation-record-itself-is-retrievable.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-verifiable-credential-as-revoked-before-the-revocation-record-itself-is-retrievable.warrant.json
# Markdown SHA-256:   f9102e9459ef51173cc79a96c2b05e2a721ea8bd8add2483d37c9c3a13f44739
# Code AST SHA-256:   98a6051b5cac13a3c4d6e819135f97ac7a88e92917f526d6a93b29545e7242f2
# Verified Classes:   StatusState, RevocationCurrencyError, StatusObservation, AdmissionGrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class StatusState(Enum):
    CLEAR = "clear"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


class RevocationCurrencyError(RuntimeError):
    """Raised when an admission decision rests on a status observation
    that is over-age, unfetchable, or otherwise not current enough to
    bound the requested admission lifetime."""


@dataclass(frozen=True)
class StatusObservation:
    state: StatusState
    issued_at: float          # issuer timestamp of the status artifact
    currency: float           # issuer-declared max age before UNKNOWN
    signature_valid: bool


@dataclass(frozen=True)
class AdmissionGrant:
    peer_id: str
    granted_at: float
    expires_at: float


def admit_peer(
    peer_id: str,
    obs: Optional[StatusObservation],
    now: float,
    requested_ttl: float,
    mutating: bool,
) -> AdmissionGrant:
    # No observation at all is UNKNOWN, never CLEAR.
    if obs is None:
        if mutating:
            raise RevocationCurrencyError(
                f"no status observation for {peer_id}; refusing mutating admission"
            )
        raise RevocationCurrencyError(
            f"no status observation for {peer_id}; re-attestation required"
        )

    if not obs.signature_valid:
        raise RevocationCurrencyError(
            f"status artifact for {peer_id} failed signature verification"
        )

    age = now - obs.issued_at
    if age > obs.currency:
        # Over-age artifact: the issuer's decision state may have moved.
        # Treat as UNKNOWN, not as the bit it carries.
        raise RevocationCurrencyError(
            f"status for {peer_id} is {age:.0f}s old, currency bound is "
            f"{obs.currency:.0f}s; refusing to admit on stale observation"
        )

    if obs.state is StatusState.REVOKED:
        raise RevocationCurrencyError(
            f"peer {peer_id} is revoked; admission refused and revocation "
            f"must be propagated to co-located brokers"
        )

    if obs.state is StatusState.UNKNOWN:
        raise RevocationCurrencyError(
            f"peer {peer_id} status is UNKNOWN; failing closed for "
            f"{'mutating' if mutating else 'read-only'} action"
        )

    # CLEAR and within currency: the grant must not outlive the currency window.
    ttl = min(requested_ttl, obs.currency - age)
    if ttl <= 0:
        raise RevocationCurrencyError(
            f"no positive admission window for {peer_id} within currency bound"
        )
    return AdmissionGrant(peer_id=peer_id, granted_at=now, expires_at=now + ttl)
