# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-peer-s-policy-attestation-is-structurally-valid-but-temporally-inc.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-peer-s-policy-attestation-is-structurally-valid-but-temporally-inc.warrant.json
# Markdown SHA-256:   b1665a57ad373dcad1e8d48ae5d1f3cce3b9a836e35c045f5aa4db4767fc575f
# Code AST SHA-256:   3e050925ccf2969d0c8d991e8025c7b161bd14179c6c6f42c8a929e5f0804a31
# Verified Classes:   TemporalIncoherence, GrantDecision, GrantEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class TemporalIncoherence(RuntimeError):
    """Raised when a federated grant's temporal envelope cannot be coherently honored."""


class GrantDecision(Enum):
    CACHEABLE = "cacheable"
    SINGLE_SHOT = "single_shot"
    RENEGOTIATE = "renegotiate"


@dataclass(frozen=True)
class GrantEnvelope:
    grant_not_after: float
    policy_valid_until: float
    next_update: float
    issued_at: float
    skew_bound: float = 60.0


def classify_grant(env: GrantEnvelope, now: float, planned_use_window: float) -> GrantDecision:
    # Skew check first: a future-dated grant is undecidable, not denied.
    if abs(env.issued_at - now) > env.skew_bound:
        raise TemporalIncoherence(
            f"clock skew {abs(env.issued_at - now):.1f}s exceeds bound {env.skew_bound}s; "
            f"grant is undecidable, route to pending-wait not denial"
        )

    horizon = min(env.grant_not_after, env.policy_valid_until, env.next_update)

    if horizon <= now:
        raise TemporalIncoherence(
            f"grant envelope lapsed: min-validity field at {horizon:.1f} <= now {now:.1f}; "
            f"renegotiate, do not retry"
        )

    if env.policy_valid_until >= now + planned_use_window and env.next_update >= now + planned_use_window:
        return GrantDecision.CACHEABLE

    if env.policy_valid_until > now and env.next_update > now:
        return GrantDecision.SINGLE_SHOT

    raise TemporalIncoherence(
        f"cannot bound use window {planned_use_window:.1f}s within envelope horizon "
        f"{horizon - now:.1f}s; renegotiate fresh attestation"
    )


def safe_cache_ttl(env: GrantEnvelope, now: float) -> float:
    # The bug from the trace: never cache on grant_not_after alone.
    ttl = min(env.grant_not_after, env.policy_valid_until, env.next_update) - now
    if ttl <= 0:
        raise TemporalIncoherence("refusing to cache a lapsed grant")
    return ttl
