# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-federated-warrant-outlives-its-cached-aaif-delegation-token.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-revoked-federated-warrant-outlives-its-cached-aaif-delegation-token.warrant.json
# Markdown SHA-256:   d9ba7cca72c09bbcaf6d078ae31f69028d9efd3903018ea31ce19e589d42bb7c
# Code AST SHA-256:   da7c0a95a464a3e9042979028c9552d9dda4474b0b2a96201cabca2d8cb8e67f
# Verified Classes:   StaleWarrantVerdictError, RevocationEndpointUnreachable, WarrantVerdict, FederatedActionGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleWarrantVerdictError(RuntimeError):
    """Raised when an action is attempted under a federated warrant whose
    revocation status cannot be confirmed within the issuer-bounded window."""
    pass


class RevocationEndpointUnreachable(StaleWarrantVerdictError):
    """Fail-closed variant: endpoint down and last verdict exceeds max_staleness."""
    pass


@dataclass(frozen=True)
class WarrantVerdict:
    jti: str
    valid: bool
    confirmed_at: float          # monotonic seconds
    max_staleness: float         # issuer-declared tolerance
    rev_check_hint: float        # issuer-suggested re-poll interval


class FederatedActionGate:
    """Enforces: verdict freshness is bound to the action, never to a session
    or checkpoint. Cached verdicts are references, not booleans."""

    def __init__(self, rp_cache_ttl: float):
        self._rp_cache_ttl = rp_cache_ttl
        self._verdicts: dict[str, WarrantVerdict] = {}

    def _freshness_window(self, v: WarrantVerdict, remaining_ttl: float) -> float:
        # RP must never widen staleness beyond issuer intent, nor beyond token life.
        return min(v.rev_check_hint, v.max_staleness, self._rp_cache_ttl, remaining_ttl)

    def _confirm(self, jti: str, rev_endpoint) -> WarrantVerdict:
        try:
            return rev_endpoint.check(jti)
        except ConnectionError as exc:
            last = self._verdicts.get(jti)
            if last is None:
                raise RevocationEndpointUnreachable(
                    f"no prior verdict for jti={jti} and endpoint unreachable"
                ) from exc
            if time.monotonic() - last.confirmed_at > last.max_staleness:
                raise RevocationEndpointUnreachable(
                    f"jti={jti} last verdict older than max_staleness "
                    f"{last.max_staleness}s; fail-closed"
                ) from exc
            return last  # still within issuer tolerance

    def authorize_action(
        self,
        jti: str,
        remaining_ttl: float,
        rev_endpoint,
        checkpoint_assertion: Optional[bool] = None,
    ) -> None:
        # A checkpointed boolean is NEVER trusted as a live verdict.
        if checkpoint_assertion is not None:
            pass  # explicitly ignored; retained only for audit contrast

        v = self._verdicts.get(jti)
        now = time.monotonic()

        if v is None or not v.valid:
            v = self._confirm(jti, rev_endpoint)
            self._verdicts[jti] = v
            now = time.monotonic()

        window = self._freshness_window(v, remaining_ttl)
        age = now - v.confirmed_at

        if age > window:
            # Stale verdict at action time: block this action, re-confirm synchronously.
            v = self._confirm(jti, rev_endpoint)
            self._verdicts[jti] = v
            age = time.monotonic() - v.confirmed_at
            if age > window:
                raise StaleWarrantVerdictError(
                    f"jti={jti} verdict age {age:.1f}s exceeds window {window:.1f}s "
                    f"at action time; refusing execution"
                )

        if not v.valid:
            raise StaleWarrantVerdictError(
                f"jti={jti} revoked at origin; action refused despite unexpired token"
            )
