# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-attestation-chain-whose-root-anchor-rotated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-attestation-chain-whose-root-anchor-rotated-mid-handoff.warrant.json
# Markdown SHA-256:   26dace6ec4e0e10db4466fc1bb8c7ce36bc89c70970a7f805f35d73ab12db952
# Code AST SHA-256:   c29a3c4f92db9838ad9d5614be73061ba0030fa6b14281e2c433fb5c8b8faa58
# Verified Classes:   AttestationStaleError, RootKeyState, AnchorDocument, AttestationChain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationStaleError(RuntimeError):
    """Raised when a chain verifies cryptographically but its root anchor
    was superseded or too stale to authorize execution at verification time."""
    pass


@dataclass
class RootKeyState:
    key_id: str
    active_from: float
    superseded_at: float | None  # None => still active


@dataclass
class AnchorDocument:
    fetched_at: float
    roots: dict[str, RootKeyState]


@dataclass
class AttestationChain:
    issued_at: float
    root_key_id: str
    provenance_blob: list["AttestationChain"]  # foreign-rooted segments carried forward


ANCHOR_FRESHNESS_BOUND = 15 * 60  # seconds


def verify_chain(chain: AttestationChain, anchor: AnchorDocument, now: float) -> None:
    # 1. Anchor must be fresh enough to make an authorization decision.
    if anchor.fetched_at < now - ANCHOR_FRESHNESS_BOUND:
        raise AttestationStaleError(
            f"anchor fetched_at={anchor.fetched_at} exceeds freshness bound; "
            f"cannot authorize at now={now}"
        )

    # 2. Root used for this chain must be active at issuance AND not superseded before now.
    root = anchor.roots.get(chain.root_key_id)
    if root is None:
        raise AttestationStaleError(
            f"root {chain.root_key_id} absent from fresh anchor document"
        )
    if chain.issued_at < root.active_from:
        raise AttestationStaleError(
            f"chain issued_at={chain.issued_at} predates root activation"
        )
    if root.superseded_at is not None and root.superseded_at <= now:
        raise AttestationStaleError(
            f"root {root.key_id} superseded at {root.superseded_at} "
            f"but chain verified at {now} (soft-mismatch zone)"
        )

    # 3. Recurse into forwarded provenance blobs — do not trust the delegator's
    #    fresh signature as a substitute for the upstream root's freshness.
    for segment in chain.provenance_blob:
        verify_chain(segment, anchor, now)


def handle_cross_org_handoff(chain: AttestationChain, anchor: AnchorDocument) -> str:
    try:
        verify_chain(chain, anchor, now=time.time())
    except AttestationStaleError as exc:
        # Fail closed: do not execute; request re-mint under the active root.
        raise AttestationStaleError(
            f"handoff aborted, re-mint required under active root: {exc}"
        ) from exc
    return "executed"
