# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-acting-on-a-revoked-warrant-after-key-rotation-propagates.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-acting-on-a-revoked-warrant-after-key-rotation-propagates.warrant.json
# Markdown SHA-256:   fabd263ac6bee7f183c0f418213a4b52de7bdacf55e6504438712e4d7ae9f9db
# Code AST SHA-256:   64abe941407e034b4f3b5716dc729b90472e6967328509b09808e4151432e888
# Verified Classes:   StaleWarrantError, CachedVerdict, WarrantVerifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a verifier would act on a warrant whose positive verdict
    is older than the issuer's maximum propagation latency (MPL)."""
    pass


@dataclass(frozen=True)
class CachedVerdict:
    subject: str
    kid: str            # signing key id this verdict was bound to
    epoch: int          # issuer revocation epoch at verification time
    verified_at: float  # monotonic seconds
    is_valid: bool


class WarrantVerifier:
    def __init__(self, issuer_mpl_seconds: float, registry):
        self.mpl = issuer_mpl_seconds
        self.registry = registry
        self._cache: dict[str, CachedVerdict] = {}

    def _fresh(self, v: CachedVerdict, now: float) -> bool:
        return (now - v.verified_at) <= self.mpl

    def verify(self, subject: str, kid: str, now: Optional[float] = None) -> bool:
        now = time.monotonic() if now is None else now
        cached = self._cache.get(subject)

        # Staleness is checked BEFORE the hit/miss branch.
        # A stale entry is a MISS, not a hit.
        if cached is not None and self._fresh(cached, now):
            # Even a fresh entry is only usable if its key epoch matches
            # the current registry epoch; rotation invalidates it.
            if cached.kid == kid and cached.epoch == self.registry.current_epoch():
                return cached.is_valid
            # epoch/kid mismatch => treat as miss, fall through to re-fetch.

        # Re-fetch from registry (fail closed on any failure).
        try:
            status = self.registry.status(subject, kid)
        except Exception as exc:
            raise StaleWarrantError(
                f"registry unreachable for {subject}/{kid}; failing closed"
            ) from exc

        verdict = CachedVerdict(
            subject=subject,
            kid=kid,
            epoch=self.registry.current_epoch(),
            verified_at=now,
            is_valid=status.is_valid,
        )
        self._cache[subject] = verdict  # key + status evicted together

        if not verdict.is_valid:
            return False
        return True

    def assert_actionable(self, subject: str, kid: str, now: Optional[float] = None) -> None:
        now = time.monotonic() if now is None else now
        cached = self._cache.get(subject)
        if cached is not None and not self._fresh(cached, now):
            raise StaleWarrantError(
                f"warrant for {subject} verified at t={cached.verified_at:.1f} "
                f"is stale (age {now - cached.verified_at:.1f}s > MPL {self.mpl}s); "
                f"refusing to act on revoked-or-unknown authority"
            )
        if not self.verify(subject, kid, now=now):
            raise StaleWarrantError(
                f"warrant for {subject}/{kid} is not valid at current epoch"
            )
