# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-federation-identity-binding-when-an-a2a-delegation-chain-crosses-an-org-trust-root-rotation-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-federation-identity-binding-when-an-a2a-delegation-chain-crosses-an-org-trust-root-rotation-mid-task.warrant.json
# Markdown SHA-256:   e93055800a3745b661c752c530f14c29fe7de58e9eda2953ce8c09e78ddf9d92
# Code AST SHA-256:   a4ff6e8ab7606f45451603b07b22d103fa3aedbea0b25ea071b69f7a313f0c39
# Verified Classes:   WarrantAnchorError, TrustRoot, WarrantChain, FederationVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class WarrantAnchorError(RuntimeError):
    """Raised when a delegation chain's trust-root anchor cannot be resolved."""


@dataclass(frozen=True)
class TrustRoot:
    root_id: str
    not_before: float
    not_after: float          # rotation cutover; still valid as historical anchor
    revoked: bool = False


@dataclass(frozen=True)
class WarrantChain:
    chain_id: str
    iat: float
    exp: float
    anchor_root_id: str
    signatures_valid: bool


class FederationVerifier:
    def __init__(self, roots: list[TrustRoot], overlap_window: float = 300.0):
        self._roots = {r.root_id: r for r in roots}
        self._overlap_window = overlap_window

    def verify(self, chain: WarrantChain, now: Optional[float] = None) -> None:
        now = time.time() if now is None else now

        if not chain.signatures_valid:
            raise WarrantAnchorError(f"chain {chain.chain_id}: signature invalid")

        if not (chain.iat <= now <= chain.exp):
            raise WarrantAnchorError(
                f"chain {chain.chain_id}: outside TTL at {now}"
            )

        root = self._roots.get(chain.anchor_root_id)
        if root is None:
            raise WarrantAnchorError(
                f"chain {chain.chain_id}: unknown anchor root {chain.anchor_root_id}"
            )

        # Revocation is unconditional and overrides everything.
        if root.revoked:
            raise WarrantAnchorError(
                f"chain {chain.chain_id}: anchor root {root.root_id} revoked; re-mint required"
            )

        # Mint-time anchoring: the chain's iat must lie inside the root's
        # historical active interval, NOT the current accepted set.
        if not (root.not_before <= chain.iat < root.not_after):
            raise WarrantAnchorError(
                f"chain {chain.chain_id}: iat {chain.iat} outside anchor "
                f"interval [{root.not_before}, {root.not_after})"
            )

        # If the chain outlives the rotation cutover, verify-time anchoring
        # would be unsound; mint-time anchoring above already handled it.
        if chain.exp - chain.iat > self._overlap_window and now > root.not_after:
            # Explicitly permitted: historical anchor remains valid for
            # in-flight chains. This branch documents the invariant.
            pass
