# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-anchor-during-cross-org-agent-federation-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-trust-anchor-during-cross-org-agent-federation-handoff.warrant.json
# Markdown SHA-256:   fda686d63f1a9017428e9fece45e5673145cf8c4fe5dd853dd5d7d1fd2f65285
# Code AST SHA-256:   dbf11fd21ba6279fb195af002a2360fe8481a57639e86d271741e345894bc2fa
# Verified Classes:   StaleTrustAnchorError, Anchor, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustAnchorError(RuntimeError):
    """Raised when a warrant's terminal root cannot be validated against a
    sufficiently fresh anchor set, or when the warrant was issued inside the
    revocation-propagation window."""
    pass


@dataclass(frozen=True)
class Anchor:
    root_id: str
    valid_from: float
    revoked_at: float | None
    fetched_at: float


@dataclass(frozen=True)
class Warrant:
    leaf_id: str
    terminal_root: str
    iat: float
    exp: float


def admit_warrant(
    warrant: Warrant,
    anchors: dict[str, Anchor],
    now: float,
    revocation_propagation_sla: float,
) -> str:
    """Return 'admitted', 'quarantined', or raise StaleTrustAnchorError.

    Invariant: TTL of any anchor view must be <= revocation_propagation_sla.
    """
    anchor = anchors.get(warrant.terminal_root)
    if anchor is None:
        raise StaleTrustAnchorError(
            f"terminal root {warrant.terminal_root} absent from anchor set; "
            f"refusing TOFU for cross-org federation"
        )

    anchor_age = now - anchor.fetched_at
    if anchor_age > revocation_propagation_sla:
        raise StaleTrustAnchorError(
            f"anchor {anchor.root_id} is {anchor_age:.0f}s stale, exceeds "
            f"revocation SLA of {revocation_propagation_sla:.0f}s; fail closed"
        )

    if now > warrant.exp:
        raise StaleTrustAnchorError(
            f"warrant {warrant.leaf_id} expired at {warrant.exp:.0f}"
        )

    if anchor.revoked_at is not None:
        if warrant.iat >= anchor.revoked_at:
            raise StaleTrustAnchorError(
                f"warrant {warrant.leaf_id} issued at {warrant.iat:.0f} "
                f"at/after root {anchor.root_id} revocation at "
                f"{anchor.revoked_at:.0f}; reject"
            )
        # iat precedes revocation, but may fall inside the propagation window.
        if warrant.iat >= anchor.revoked_at - revocation_propagation_sla:
            return "quarantined"

    return "admitted"
