# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-replayed-capability-attestation-when-the-attestation-chain-is-valid-but-the-epoch-has-rolled.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-replayed-capability-attestation-when-the-attestation-chain-is-valid-but-the-epoch-has-rolled.warrant.json
# Markdown SHA-256:   74b889cdafe636dff623ee44ebedc902750217f789a8e2f2fa8fee16f8a6f59d
# Code AST SHA-256:   461d83e8ad45f96f133c378043182aae3a410fa31d1ccc82913786b7dccc0432
# Verified Classes:   EpochStaleError, Attestation, FederationBroker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict


class EpochStaleError(RuntimeError):
    """Raised when a signature-valid token was minted under a non-current epoch."""


@dataclass(frozen=True)
class Attestation:
    issuer: str
    epoch: int
    scopes: frozenset
    signature_valid: bool


class FederationBroker:
    def __init__(self, epoch_ledger: Dict[str, int]):
        # Durable, monotonic. Must survive restart; must never be re-derived
        # from retained key material (that is how current_epoch silently drops).
        self._ledger = dict(epoch_ledger)
        self._retained_epochs: Dict[str, set] = {}

    def retain_historical_key(self, issuer: str, epoch: int) -> None:
        self._retained_epochs.setdefault(issuer, set()).add(epoch)

    def current_epoch(self, issuer: str) -> int:
        if issuer not in self._ledger:
            raise EpochStaleError(f"no epoch ledger entry for issuer {issuer!r}")
        return self._ledger[issuer]

    def verify_for_consumption(self, token: Attestation) -> Attestation:
        # Gate 1: chain verification (historical question).
        if not token.signature_valid:
            raise EpochStaleError(f"signature chain invalid for {token.issuer!r}")
        if token.epoch not in self._retained_epochs.get(token.issuer, set()):
            raise EpochStaleError(
                f"epoch {token.epoch} of {token.issuer!r} not in retained key set"
            )
        # Gate 2: epoch currency (present-tense question). This is the gate
        # that is missing in the observed defect. It must run at consumption.
        live = self.current_epoch(token.issuer)
        if token.epoch != live:
            raise EpochStaleError(
                f"replayed token: {token.issuer!r} epoch {token.epoch} "
                f"!= current {live}; scopes {sorted(token.scopes)} withdrawn"
            )
        return token


def consume_handoff(broker: FederationBroker, token: Attestation) -> Attestation:
    # Consumer must receive EpochStale distinctly from generic invalid so it
    # can decide "re-attest" vs "do not retry".
    return broker.verify_for_consumption(token)
