# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-peer-when-aaif-rotation-forks-the-trust-anchor-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-trusting-a-revoked-peer-when-aaif-rotation-forks-the-trust-anchor-chain.warrant.json
# Markdown SHA-256:   530f4136e456c251bda8c0f292508fc583df83c2de1df43cc390b8f08465b1be
# Code AST SHA-256:   4eb659bbb56c240327edb8c806061b0b3b5d160aae32d6fc7bf16e6413e586e8
# Verified Classes:   StaleAnchorError, UnknownAnchorError, ResolvedChain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAnchorError(RuntimeError):
    """Raised when a chained warrant resolves to an anchor epoch that lags the verifier's current epoch beyond the skew budget."""


class UnknownAnchorError(RuntimeError):
    """Raised when a re-walk encounters an anchor absent from the local directory during a rotation in flight."""


@dataclass(frozen=True)
class ResolvedChain:
    leaf_warrant_id: str
    anchor_id: str
    anchor_epoch: int
    resolved_at: float


SKEW_BUDGET_SECONDS = 5.0


def admit_peer(
    chain: ResolvedChain,
    verifier_epoch: int,
    epoch_published_at: float,
    now: float | None = None,
) -> bool:
    now = time.monotonic() if now is None else now

    # Rotation in flight: the successor anchor is not yet in the directory.
    # Fail closed. Never fall back to the superseded (likely revoked) anchor.
    if chain.anchor_epoch > verifier_epoch:
        raise UnknownAnchorError(
            f"anchor {chain.anchor_id} epoch {chain.anchor_epoch} ahead of "
            f"verifier epoch {verifier_epoch}; rotation in flight, suspend admission"
        )

    # Revocation/freshness binding: the chain must be live under the current epoch,
    # or within an explicitly bounded skew window measured from epoch publication.
    epoch_age = now - epoch_published_at
    if chain.anchor_epoch < verifier_epoch and epoch_age > SKEW_BUDGET_SECONDS:
        raise StaleAnchorError(
            f"anchor {chain.anchor_id} epoch {chain.anchor_epoch} < verifier "
            f"epoch {verifier_epoch} (epoch age {epoch_age:.1f}s > budget "
            f"{SKEW_BUDGET_SECONDS}s); chain may reference a revoked anchor"
        )

    return True
