# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-capability-warrant-before-the-peer-s-revocation-epoch-has-converged.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-capability-warrant-before-the-peer-s-revocation-epoch-has-converged.warrant.json
# Markdown SHA-256:   7e1b1f5b584dadbe129658087167ffbd241a97bb1eee0e6b4f8a3b3fca098c2f
# Code AST SHA-256:   cb1f968bb09836f71f56104f192a8b9ec7f7222c84be1a3d211a468076f0abea
# Verified Classes:   RevocationEpochInversion, Warrant, DiscoveryResponse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict


class RevocationEpochInversion(RuntimeError):
    """Raised when a warrant is admitted despite the consumer's revocation
    head for the issuer lagging the responder's head at response time."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    epoch: int
    skill: str


@dataclass(frozen=True)
class DiscoveryResponse:
    warrant: Warrant
    responder: str
    # responder's revocation head for the warrant's issuer, at response time
    responder_rev_head: Dict[str, int]


def admit_warrant(
    resp: DiscoveryResponse,
    local_rev_head: Dict[str, int],
    revoked: Dict[str, int],  # warrant_id -> revocation epoch
) -> Warrant:
    w = resp.warrant

    # Guardrail 1: never admit on a lagging revocation view.
    local = local_rev_head.get(w.issuer, -1)
    responder = resp.responder_rev_head.get(w.issuer, -1)
    if local < responder:
        raise RevocationEpochInversion(
            f"refusing {w.warrant_id}: local rev head for {w.issuer}={local} "
            f"< responder {resp.responder}={responder}; converge before admitting"
        )

    # Guardrail 2: revocation keyed by issuer+warrant, not responder+skill.
    if w.warrant_id in revoked and revoked[w.warrant_id] >= w.epoch:
        raise RevocationEpochInversion(
            f"refusing {w.warrant_id}: revoked at epoch "
            f"{revoked[w.warrant_id]} (warrant epoch {w.epoch})"
        )

    return w
