# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-aaif-credential-chain-is-revoked-mid-execution-but-its-cached-warrant-token-still-validates-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-delegated-aaif-credential-chain-is-revoked-mid-execution-but-its-cached-warrant-token-still-validates-locally.warrant.json
# Markdown SHA-256:   d33d27ae03aecd3c8370c784036e71c084de76d995345f6e02cf9a9f16050288
# Code AST SHA-256:   de635d819e035c1825d85fa8d6d3f419cbb9290e1dd23d20a662b7fc883fa6b3
# Verified Classes:   RevocationIndeterminateError, WarrantRevokedError, CachedWarrant, WarrantCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationIndeterminateError(RuntimeError):
    """Raised when a cached warrant's revocation freshness bound is exceeded
    and the issuer cannot be reached to re-confirm. Indeterminate != valid."""


class WarrantRevokedError(PermissionError):
    """Raised on an affirmative revocation signal (epoch bump or 410 Gone).
    Never route this to a stale-cache-permitted branch."""


@dataclass(frozen=True)
class CachedWarrant:
    warrant_id: str
    embedded_epoch: int
    last_epoch_observation: float  # monotonic seconds
    not_after: float


class WarrantCache:
    def __init__(self, issuer, l_max_seconds: float = 5.0):
        self._issuer = issuer
        self._l_max = l_max_seconds
        self._store: dict[str, CachedWarrant] = {}

    def admit(self, w: CachedWarrant) -> None:
        self._store[w.warrant_id] = w

    def authorize(self, warrant_id: str, now: float | None = None) -> CachedWarrant:
        now = time.monotonic() if now is None else now
        w = self._store.get(warrant_id)
        if w is None:
            raise RevocationIndeterminateError(
                f"no cached warrant {warrant_id}; cannot authorize without observation"
            )

        # Freshness bound: outside L_max the token is indeterminate, not valid.
        if now - w.last_epoch_observation >= self._l_max:
            try:
                observed = self._issuer.ancestor_epoch(warrant_id)
            except self._issuer.TransportError as e:
                # Transport failure -> indeterminate -> deny. Do NOT re-admit cache.
                raise RevocationIndeterminateError(
                    f"cannot confirm revocation epoch for {warrant_id} within "
                    f"L_max={self._l_max}s: {e}"
                ) from e

            if observed is None:
                # 410 Gone for an ancestor: affirmative revocation, terminal.
                raise WarrantRevokedError(
                    f"ancestor of {warrant_id} returned Gone; delegation revoked"
                )
            if observed > w.embedded_epoch:
                raise WarrantRevokedError(
                    f"{warrant_id} embedded epoch {w.embedded_epoch} < "
                    f"observed {observed}"
                )
            w = CachedWarrant(
                warrant_id=w.warrant_id,
                embedded_epoch=observed,
                last_epoch_observation=now,
                not_after=w.not_after,
            )
            self._store[warrant_id] = w

        if now >= w.not_after:
            raise WarrantRevokedError(f"{warrant_id} past not_after")
        return w
