# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-task-whose-policy-warrant-was-minted-against-a-stale-reputation-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-task-whose-policy-warrant-was-minted-against-a-stale-reputation-snapshot.warrant.json
# Markdown SHA-256:   b59d97467f4837e5e13e903b30b19b50c2c40de9df82e7c498cd40cc4debb160
# Code AST SHA-256:   5b1896b89530e8abbec221a413363b7c6ac480b2b455c1103bf3806a85f78307
# Verified Classes:   StaleWarrantError, LedgerUnreachableError, Warrant, Ledger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Protocol


class StaleWarrantError(RuntimeError):
    """Raised when a federated warrant's reputation snapshot is too old to admit on."""


class LedgerUnreachableError(RuntimeError):
    """Raised when a synchronous ledger re-query is required but fails."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    capability: str
    reputation: float          # embedded score, valid only at snapshot_epoch
    snapshot_epoch: int
    signature_valid: bool


class Ledger(Protocol):
    def current_epoch(self) -> int: ...
    def score_at(self, issuer: str, epoch: int) -> float | None: ...


# Freshness windows are per-capability; high-blast-radius caps get tight bounds.
FRESHNESS: dict[str, tuple[int, int]] = {
    "read:artifact":      (50, 200),
    "write:shared_store": (5,  20),
    "delegate:warrant":   (2,  8),
}
DEFAULT_FRESHNESS = (5, 20)
MIN_SCORE = 0.85


def admit(warrant: Warrant, ledger: Ledger, *, propagate: bool = False) -> Warrant:
    if not warrant.signature_valid:
        raise StaleWarrantError(f"invalid signature from {warrant.issuer}")

    delta_max, delta_hard = FRESHNESS.get(warrant.capability, DEFAULT_FRESHNESS)
    current = ledger.current_epoch()
    delta = current - warrant.snapshot_epoch

    if delta < 0:
        # Receiver's ledger is behind the issuer's — clock skew across orgs.
        raise StaleWarrantError(
            f"negative epoch delta ({delta}) for {warrant.issuer}; "
            "ledger skew, refuse rather than guess"
        )

    if delta <= delta_max:
        effective = warrant.reputation
        effective_epoch = warrant.snapshot_epoch
    elif delta <= delta_hard:
        # Branch 2: must refresh synchronously, and must fail closed.
        try:
            fresh = ledger.score_at(warrant.issuer, current)
        except Exception as exc:  # transport, timeout, partition
            raise LedgerUnreachableError(
                f"cannot refresh stale warrant for {warrant.issuer} "
                f"(delta={delta}); refusing admission rather than "
                "falling back to embedded score"
            ) from exc
        if fresh is None:
            raise StaleWarrantError(
                f"no ledger record for {warrant.issuer} at epoch {current}"
            )
        effective = fresh
        effective_epoch = current
    else:
        # Branch 3: too stale to repair. Reject and signal the issuer.
        raise StaleWarrantError(
            f"warrant from {warrant.issuer} is {delta} epochs stale "
            f"(hard limit {delta_hard}); likely replay or ledger partition"
        )

    if effective < MIN_SCORE:
        raise StaleWarrantError(
            f"{warrant.issuer} effective score {effective:.2f} < {MIN_SCORE} "
            f"at epoch {effective_epoch}"
        )

    if propagate:
        # Re-stamp to the epoch we actually verified against, never inherit.
        return Warrant(
            issuer=warrant.issuer,
            capability=warrant.capability,
            reputation=effective,
            snapshot_epoch=effective_epoch,
            signature_valid=warrant.signature_valid,
        )
    return warrant
