# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-federated-trust-anchor-mid-handoff-policy-epoch-skew-across-organizational-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-federated-trust-anchor-mid-handoff-policy-epoch-skew-across-organizational-boundaries.warrant.json
# Markdown SHA-256:   5d846094b56bb23877e4ff1a4865322e15d391f4c39ad39a4e91c24c0c0b76e5
# Code AST SHA-256:   4a5eab2d16022784fa74b40d96d3f6ac3c06e5764b36287f38ac02724451862d
# Verified Classes:   AnchorCurrencyUnconfirmed, EpochMismatch, TrustAnchor, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AnchorCurrencyUnconfirmed(RuntimeError):
    """Raised when a receiver cannot prove its trust anchor matches the issuer's live policy epoch."""


class EpochMismatch(RuntimeError):
    """Raised when the warrant's asserted epoch differs from the receiver's confirmed anchor epoch."""


@dataclass
class TrustAnchor:
    issuer: str
    epoch: int
    not_after: float
    last_confirmed: float  # monotonic timestamp of last issuer epoch confirmation


@dataclass
class Warrant:
    issuer: str
    asserted_epoch: int
    capability: str
    signature_valid: bool


def admit_handoff(
    anchor: TrustAnchor,
    warrant: Warrant,
    fetch_issuer_epoch,          # callable(issuer) -> int, may raise on unreachable
    staleness_window: float = 30.0,
    now: float | None = None,
) -> bool:
    now = time.monotonic() if now is None else now

    if not warrant.signature_valid:
        raise EpochMismatch("terminal: warrant signature invalid")  # distinct terminal class in practice

    if warrant.issuer != anchor.issuer:
        raise EpochMismatch(f"issuer mismatch: warrant={warrant.issuer} anchor={anchor.issuer}")

    # Currency check FIRST: an unconfirmed anchor cannot be used to validate epoch equality,
    # because both artifacts could be stale together (the observed failure).
    if (now - anchor.last_confirmed) > staleness_window:
        try:
            live_epoch = fetch_issuer_epoch(anchor.issuer)
        except Exception as exc:
            raise AnchorCurrencyUnconfirmed(
                f"anchor for {anchor.issuer} unconfirmed (last={now - anchor.last_confirmed:.1f}s ago) "
                f"and issuer unreachable: {exc}"
            ) from exc
        if live_epoch != anchor.epoch:
            raise AnchorCurrencyUnconfirmed(
                f"cached anchor epoch {anchor.epoch} superseded by live epoch {live_epoch}; "
                f"refusing to admit against stale anchor"
            )
        anchor.last_confirmed = now  # only after live confirmation

    # Now epoch equality is meaningful, because anchor currency is established.
    if warrant.asserted_epoch != anchor.epoch:
        raise EpochMismatch(
            f"warrant epoch {warrant.asserted_epoch} != confirmed anchor epoch {anchor.epoch}; "
            f"re-mint required"
        )

    if now > anchor.not_after:
        raise AnchorCurrencyUnconfirmed(f"anchor not_after lapsed at {anchor.not_after}")

    return True
