# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-per-invocation-capability-token-expiry-as-a-hard-execution-barrier-rather-than-a-retryable-condition.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-per-invocation-capability-token-expiry-as-a-hard-execution-barrier-rather-than-a-retryable-condition.warrant.json
# Markdown SHA-256:   55fb47981d43c72bc7aba71e672950032e1180b1e112608671d3a246e0ef935a
# Code AST SHA-256:   f7dd0d21de849b1c19b49bf98577f8acfa618136c8fa6c6bf408d2fd78971307
# Verified Classes:   CapabilityError, CapabilityExpired, PolicyDenied, StaleTokenReuse, RejectionClass, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CapabilityError(RuntimeError):
    """Base class for capability-token enforcement failures."""


class CapabilityExpired(CapabilityError):
    """Token was valid at mint but aged out before enforcement. Temporal, re-mintable."""


class PolicyDenied(CapabilityError):
    """PDP refused to mint or scope the capability. Semantic, terminal."""


class StaleTokenReuse(CapabilityError):
    """Agent attempted to re-present a token it already knows is expired. Forbidden."""


class RejectionClass(Enum):
    EXPIRED = "capability_expired"
    DENIED = "policy_denied"
    SCOPE_MISMATCH = "scope_mismatch"


@dataclass(frozen=True)
class Token:
    token_id: str
    minted_at: float
    ttl_s: float
    scope: str

    def is_expired(self, now: float) -> bool:
        return now >= self.minted_at + self.ttl_s


def execute_gated_call(
    token: Token,
    now: float,
    reissue,
    max_remints: int = 1,
) -> str:
    """Enforce the expiry-as-hard-barrier invariant.

    `reissue` is a callable that mints a fresh token through the PDP and
    raises PolicyDenied if the PDP refuses. It must never return the same
    token bytes it was given.
    """
    remints = 0
    current = token
    while True:
        if current.is_expired(now):
            if remints >= max_remints:
                raise CapabilityExpired(
                    f"token {current.token_id} expired at "
                    f"{current.minted_at + current.ttl_s:.2f}s; "
                    f"re-mint budget exhausted ({remints}/{max_remints})"
                )
            fresh = reissue(current.scope)
            if fresh.token_id == current.token_id:
                raise StaleTokenReuse(
                    f"reissue returned stale token {fresh.token_id}; "
                    "re-presenting an expired token is forbidden"
                )
            current = fresh
            remints += 1
            continue
        # Enforcement point: token is live. Any rejection here is semantic.
        outcome = _enforce(current, now)
        if outcome is RejectionClass.EXPIRED:
            # Race: expired between our check and the PEP. One re-mint allowed.
            if remints >= max_remints:
                raise CapabilityExpired(
                    f"PEP rejected {current.token_id} as expired after re-mint"
                )
            current = reissue(current.scope)
            remints += 1
            continue
        if outcome in (RejectionClass.DENIED, RejectionClass.SCOPE_MISMATCH):
            raise PolicyDenied(
                f"terminal denial {outcome.value} for scope {current.scope}; "
                "retry is policy evasion"
            )
        return "ok"


def _enforce(token: Token, now: float) -> RejectionClass | None:
    """Stub for the PEP. Real implementation consults the policy engine."""
    if token.is_expired(now):
        return RejectionClass.EXPIRED
    return None
