# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-attestation-whose-trust-anchor-freshness-window-has-already-elapsed-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-attestation-whose-trust-anchor-freshness-window-has-already-elapsed-mid-handshake.warrant.json
# Markdown SHA-256:   e840307df0f2828cb5c6a225b0a56450f6857b6ee5b20d8d0c45beefae1e0ffa
# Code AST SHA-256:   d757f905a4416584b313b009e711264cb77dd94a856639967d2e9f866e03341b
# Verified Classes:   StaleAttestationError, AnchorGenerationMismatch, Attestation, AnchorState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a federated capability attestation cannot be proven fresh at use time."""


class AnchorGenerationMismatch(StaleAttestationError):
    """Raised when the anchor handle resolves to a different generation than the one signed under."""


@dataclass(frozen=True)
class Attestation:
    anchor_id: str
    anchor_generation: int
    not_after: float          # anchor authority clock, seconds since epoch
    granted_scope: str


@dataclass(frozen=True)
class AnchorState:
    anchor_id: str
    generation: int
    not_after: float
    reachable: bool


def verify_at_use(
    attestation: Attestation,
    resolve_anchor,               # () -> AnchorState, may raise on unreachable
    delta_revalidate: float,      # worst-case RTT to authority + verifier clock uncertainty
    now: Optional[float] = None,
) -> None:
    """Re-verify an attestation immediately before capability use.

    Raises StaleAttestationError (or subclass) if the grant cannot be proven
    live at this instant. Never falls back to a cached boolean.
    """
    now = time.time() if now is None else now

    try:
        anchor = resolve_anchor()
    except Exception as exc:  # unreachable authority is indistinguishable from rotation
        raise StaleAttestationError(
            f"anchor {attestation.anchor_id} unreachable; cannot prove freshness"
        ) from exc

    if not anchor.reachable:
        raise StaleAttestationError(
            f"anchor {attestation.anchor_id} reported unreachable"
        )

    if anchor.generation != attestation.anchor_generation:
        raise AnchorGenerationMismatch(
            f"attestation signed under generation {attestation.anchor_generation}, "
            f"anchor now at generation {anchor.generation}; grant is anchored to a "
            f"superseded root and must be refused"
        )

    if now + delta_revalidate >= anchor.not_after:
        raise StaleAttestationError(
            f"attestation expires at {anchor.not_after:.3f} but revalidation "
            f"deadline is {now + delta_revalidate:.3f}; refusing use"
        )


def invoke_capability(
    attestation: Attestation,
    resolve_anchor,
    delta_revalidate: float,
    tool_call,
):
    # Hard gate: re-verify at the instant of use, not at handshake time.
    verify_at_use(attestation, resolve_anchor, delta_revalidate)
    return tool_call()
