# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-capability-token-when-the-revocation-epoch-advances-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-revoked-capability-token-when-the-revocation-epoch-advances-mid-tool-call.warrant.json
# Markdown SHA-256:   d186975a538350e37ad03acc14fbd6f13ab7a69d2f7634fe37c1b0c69ae03ed1
# Code AST SHA-256:   a79bee23c5257941cc937f788c6d2b75edfcd60c6dcbcd6c3b58758ccabde2c9
# Verified Classes:   RevokedCapabilityError, StaleEpochCacheError, CapabilityToken, EpochCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevokedCapabilityError(RuntimeError):
    """Raised when a capability token's mint epoch is behind the issuer epoch."""
    pass


class StaleEpochCacheError(RuntimeError):
    """Raised when the verifier cannot prove epoch freshness within bound."""
    pass


@dataclass
class CapabilityToken:
    scope: str
    mint_epoch: int
    expiry: float  # absolute wall-clock seconds


@dataclass
class EpochCache:
    epoch: int
    refreshed_at: float


HIGH_RISK_PREFIXES = ("filesystem:write", "external:send", "spend:")


def authorize(
    token: CapabilityToken,
    cache: EpochCache,
    issuer_epoch_now: int,
    staleness_bound: float,
    commit_budget: float,
    now: float | None = None,
) -> int:
    """Return the epoch the commit is authorized under, or raise.

    Enforces: commit is permitted only if the verifier's epoch equals the
    token's mint epoch, the cache is within the staleness bound, and the
    token has enough TTL left to cover the commit budget.
    """
    now = time.time() if now is None else now

    if token.expiry <= now + commit_budget:
        raise RevokedCapabilityError(
            f"token for {token.scope} expires in {token.expiry - now:.1f}s, "
            f"below commit budget {commit_budget:.1f}s"
        )

    if token.mint_epoch < issuer_epoch_now:
        raise RevokedCapabilityError(
            f"token minted under epoch {token.mint_epoch}, issuer now at "
            f"{issuer_epoch_now}: revoked during propagation window"
        )

    cache_age = now - cache.refreshed_at
    high_risk = token.scope.startswith(HIGH_RISK_PREFIXES)

    if cache.epoch != token.mint_epoch:
        raise StaleEpochCacheError(
            f"verifier epoch {cache.epoch} != token epoch {token.mint_epoch}"
        )

    if cache_age > staleness_bound:
        if high_risk:
            raise StaleEpochCacheError(
                f"cache age {cache_age:.1f}s exceeds bound {staleness_bound:.1f}s "
                f"on high-risk scope {token.scope}; synchronous re-attest required"
            )
        raise StaleEpochCacheError(
            f"cache age {cache_age:.1f}s exceeds bound on {token.scope}"
        )

    return cache.epoch
