# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-peer-s-capability-warrant-after-a-trust-broker-rotation-and-how-does-stale-warrant-propagation-c.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-peer-s-capability-warrant-after-a-trust-broker-rotation-and-how-does-stale-warrant-propagation-c.warrant.json
# Markdown SHA-256:   3ed2cdb94b9972d3b7a3eba0a72632fa79c9076d50d802d59a7851c024b30fce
# Code AST SHA-256:   e499f5ecc301d60a9caff6eeb2df6b03257e7eef86dd6bdb0d725a431c89a7d8
# Verified Classes:   WarrantEpochStale, Warrant, LocalTrustState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantEpochStale(RuntimeError):
    """Raised when a presented warrant's key_generation is below the local
    trust epoch, even though signature, expiry, and scope all pass. This is a
    continuity refusal, not a validation failure: the peer must re-mint."""

    def __init__(self, warrant_generation: int, local_epoch: int, peer_id: str):
        self.warrant_generation = warrant_generation
        self.local_epoch = local_epoch
        self.peer_id = peer_id
        super().__init__(
            f"warrant gen {warrant_generation} < local epoch {local_epoch} "
            f"for peer {peer_id}; re-mint required"
        )


@dataclass
class Warrant:
    subject: str
    key_generation: int
    expiry: float
    scope: frozenset
    signature_valid: bool


@dataclass
class LocalTrustState:
    observed_epoch: int
    open_sessions: dict  # session_id -> warrant key_generation at open time


def admit_handoff_warrant(
    state: LocalTrustState,
    warrant: Warrant,
    requested_action: str,
    now: float,
    session_id: Optional[str] = None,
) -> str:
    """Admit or refuse a warrant arriving on a checkpoint handoff.

    Order matters: generation floor is checked BEFORE signature so that the
    broker's revocation grace window cannot launder a stale grant.
    """
    # 1. Generation floor — the invariant this article is about.
    if warrant.key_generation < state.observed_epoch:
        # Resume-under-existing-warrant is the only permitted exception.
        if session_id is not None and session_id in state.open_sessions:
            if state.open_sessions[session_id] == warrant.key_generation:
                return "legacy_resume"
        raise WarrantEpochStale(
            warrant_generation=warrant.key_generation,
            local_epoch=state.observed_epoch,
            peer_id=warrant.subject,
        )

    # 2. Signature, expiry, scope — only meaningful above the floor.
    if not warrant.signature_valid:
        raise ValueError("signature invalid")
    if warrant.expiry <= now:
        raise ValueError("warrant expired")
    if requested_action not in warrant.scope:
        raise ValueError("action outside warrant scope")

    return "admitted"


def on_authenticated_rotation(state: LocalTrustState, new_generation: int) -> None:
    """Advance the epoch floor. MUST be called only from a root-signed
    rotation announcement, never from a peer claim."""
    if new_generation <= state.observed_epoch:
        return
    state.observed_epoch = new_generation
