# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-rotated-signing-key-as-authoritative-before-its-own-cached-registry-view-expires.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-rotated-signing-key-as-authoritative-before-its-own-cached-registry-view-expires.warrant.json
# Markdown SHA-256:   1014f837652f7e4d1db9eaf8fc197b9dd86b0ff09b197dc53821390a9221548d
# Code AST SHA-256:   ebc9e9299637327e117291eb1f619b47f7132c0573125c4ad34aca4faced6c20
# Verified Classes:   KeyResolutionUndecidable, KeyRecord, Warrant, FederatedKeyCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class KeyResolutionUndecidable(RuntimeError):
    """Raised when a warrant's signing key cannot be proven current at iat
    and synchronous resolution did not disambiguate forgery from stale cache."""
    pass


@dataclass
class KeyRecord:
    kid: str
    valid_from: float
    revoked_at: float | None = None


@dataclass
class Warrant:
    issuer_id: str
    kid: str | None
    iat: float
    exp: float
    signature_valid_under: str  # kid the signature actually verifies against


class FederatedKeyCache:
    """Keyed on (issuer_id, kid). Async gossip populates it; synchronous
    resolution bypasses it on verification failure."""

    def __init__(self, ttl: float, propagation_p99: float):
        if ttl >= propagation_p99:
            raise KeyResolutionUndecidable(
                f"key-cache ttl {ttl}s >= propagation p99 {propagation_p99}s; "
                "stale window is unbounded by design"
            )
        self.ttl = ttl
        self._cache: dict[tuple[str, str], tuple[KeyRecord, float]] = {}
        self._authoritative: dict[str, list[KeyRecord]] = {}

    def publish_rotation(self, issuer_id: str, record: KeyRecord) -> None:
        self._authoritative.setdefault(issuer_id, []).append(record)

    def _sync_resolve(self, issuer_id: str, kid: str) -> KeyRecord | None:
        for rec in self._authoritative.get(issuer_id, []):
            if rec.kid == kid:
                return rec
        return None

    def verify(self, warrant: Warrant, now: float) -> bool:
        if now > warrant.exp:
            return False
        if warrant.kid is None:
            raise KeyResolutionUndecidable(
                f"warrant from {warrant.issuer_id} carries no kid; "
                "cannot bind signature to a key generation"
            )
        cached = self._cache.get((warrant.issuer_id, warrant.kid))
        if cached is not None:
            rec, fetched_at = cached
            if now - fetched_at <= self.ttl:
                if rec.revoked_at is not None and rec.revoked_at <= now:
                    return False
                if rec.valid_from <= warrant.iat:
                    return True
        # Cache miss or stale: synchronous resolution is mandatory before
        # concluding forgery. This is the guardrail.
        rec = self._sync_resolve(warrant.issuer_id, warrant.kid)
        if rec is None:
            raise KeyResolutionUndecidable(
                f"issuer {warrant.issuer_id} has no record of kid {warrant.kid}; "
                "cannot distinguish forgery from unpropagated rotation"
            )
        if rec.revoked_at is not None and rec.revoked_at <= now:
            return False
        if rec.valid_from > warrant.iat:
            raise KeyResolutionUndecidable(
                f"kid {warrant.kid} valid_from {rec.valid_from} > warrant iat "
                f"{warrant.iat}; warrant predates its own signing key"
            )
        self._cache[(warrant.issuer_id, warrant.kid)] = (rec, now)
        return warrant.signature_valid_under == warrant.kid
