# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-federation-anchor-that-outlives-the-key-material-it-was-minted-from.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-federation-anchor-that-outlives-the-key-material-it-was-minted-from.warrant.json
# Markdown SHA-256:   90274e1ab713a16ab9689d21788ef11e4c2542eb1726735100af23c9cda29125
# Code AST SHA-256:   26c49d988aac4a6ea9a2c38a9ac59b644916f5ba742b2414e51939083bc5fba0
# Verified Classes:   StaleAnchorEpoch, AnchorRefreshFailed, AnchorSnapshot, LeafAttestation, FederatedVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict


class StaleAnchorEpoch(RuntimeError):
    """Raised when a leaf was issued after the verifier's anchor snapshot was taken."""
    pass


class AnchorRefreshFailed(RuntimeError):
    """Raised when a synchronous anchor refresh cannot restore a usable epoch."""
    pass


@dataclass
class AnchorSnapshot:
    keys: Dict[str, dict]          # kid -> key material
    fetched_at: float              # unix seconds; the moment of last evidence
    skew_tolerance: float = 60.0   # clock skew allowance

    def max_leaf_iat(self) -> float:
        return self.fetched_at + self.skew_tolerance


@dataclass
class LeafAttestation:
    kid: str
    iat: float                     # issued-at, unix seconds
    exp: float
    signature_ok: bool


@dataclass
class FederatedVerifier:
    anchor: AnchorSnapshot
    refresh_fn: object             # callable() -> AnchorSnapshot
    _refresh_in_flight: bool = field(default=False, init=False)

    def _refresh(self) -> None:
        if self._refresh_in_flight:
            raise AnchorRefreshFailed("concurrent refresh already in flight; refusing to proceed on stale anchor")
        self._refresh_in_flight = True
        try:
            self.anchor = self.refresh_fn()
        finally:
            self._refresh_in_flight = False

    def verify(self, leaf: LeafAttestation, now: float) -> None:
        if not leaf.signature_ok:
            raise StaleAnchorEpoch(f"signature invalid for kid={leaf.kid}")
        if leaf.exp <= now:
            raise StaleAnchorEpoch(f"leaf expired: exp={leaf.exp} now={now}")
        if leaf.kid not in self.anchor.keys:
            # unknown kid: safe-ish to retry, but still must re-check iat after refresh
            self._refresh()
            if leaf.kid not in self.anchor.keys:
                raise StaleAnchorEpoch(f"kid={leaf.kid} absent after refresh")
        # THE BOUNDARY: issuance must be bounded by anchor evidence, not just expiry.
        if leaf.iat > self.anchor.max_leaf_iat():
            self._refresh()
            if leaf.iat > self.anchor.max_leaf_iat():
                raise StaleAnchorEpoch(
                    f"leaf iat={leaf.iat} exceeds anchor evidence horizon "
                    f"{self.anchor.max_leaf_iat()} (fetched_at={self.anchor.fetched_at}); "
                    f"refusing to vouch for signer epoch we never observed"
                )
