# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-revocation-epoch-has-advanced-beyond-its-own-cached-leaf-state.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-revocation-epoch-has-advanced-beyond-its-own-cached-leaf-state.warrant.json
# Markdown SHA-256:   7260161d72e1f4b2b7c47eb492fd1cbc018446588b66c61e4563f1f630d4e06c
# Code AST SHA-256:   c46f31232a1cd2c196413c92eebff4a754d9e2e77f5ca3965d14cabd2ed843c2
# Verified Classes:   CapabilityLivenessError, RevocationProvenError, FreshnessDeficitError, LivenessUnavailableError, DelegationLink, DelegatedCapability, RevocationView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class CapabilityLivenessError(RuntimeError):
    """Base class for failures to establish that a delegated capability is live."""


class RevocationProvenError(CapabilityLivenessError):
    """An ancestor or the leaf is provably revoked. Terminal; do not re-mint."""


class FreshnessDeficitError(CapabilityLivenessError):
    """Cache is too stale to prove liveness. Retryable via synchronous refresh only."""


class LivenessUnavailableError(CapabilityLivenessError):
    """Revocation view is unhealthy or token lacks an issuance epoch. Halt."""


@dataclass(frozen=True)
class DelegationLink:
    token_id: str
    issuance_epoch: int


@dataclass(frozen=True)
class DelegatedCapability:
    leaf_id: str
    issuance_epoch: int
    ancestor_chain: tuple[DelegationLink, ...]  # ordered root -> parent


@dataclass(frozen=True)
class RevocationView:
    epoch: int
    revoked_ids: frozenset[str]
    signature_valid: bool
    last_poll_monotonic: float


def authorize_delegated_call(
    cap: DelegatedCapability,
    view: RevocationView,
    delta: int,
    max_staleness_seconds: float,
    now_monotonic: float,
) -> None:
    # Guardrail 0: the view must be trustworthy at all.
    if not view.signature_valid:
        raise LivenessUnavailableError(
            f"revocation view signature invalid at epoch {view.epoch}; "
            "cannot reason about liveness"
        )
    if (now_monotonic - view.last_poll_monotonic) > max_staleness_seconds:
        raise LivenessUnavailableError(
            f"revocation poller stale by "
            f"{now_monotonic - view.last_poll_monotonic:.1f}s; halting"
        )

    # Guardrail 1: token must carry an issuance epoch to anchor freshness.
    if cap.issuance_epoch is None:
        raise LivenessUnavailableError(
            f"capability {cap.leaf_id} has no embedded issuance epoch; "
            "structurally unverifiable for liveness"
        )

    # Guardrail 2: freshness dominance. Cache must dominate the token's
    # entire vulnerable window, not merely be newer than the token.
    if view.epoch < cap.issuance_epoch + delta:
        raise FreshnessDeficitError(
            f"cached epoch {view.epoch} < issuance {cap.issuance_epoch} + "
            f"delta {delta}; liveness unprovable, refresh required "
            f"(do NOT re-mint)"
        )

    # Guardrail 3: ancestor revocation is inherited by all descendants.
    for link in cap.ancestor_chain:
        if link.token_id in view.revoked_ids:
            raise RevocationProvenError(
                f"ancestor {link.token_id} revoked at epoch {view.epoch}; "
                f"descendant {cap.leaf_id} is dead (propagate revocation, "
                f"do not retry)"
            )

    # Guardrail 4: leaf revocation, checked only after ancestors so that a
    # revoked ancestor is reported as such rather than masked by a live leaf.
    if cap.leaf_id in view.revoked_ids:
        raise RevocationProvenError(
            f"leaf {cap.leaf_id} revoked at epoch {view.epoch}"
        )

    # Freshness dominated, no ancestor or leaf revocation: proceed.
    return None
