# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-delegation-chains-that-outlive-their-attenuated-token-s-revocation-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-delegation-chains-that-outlive-their-attenuated-token-s-revocation-horizon.warrant.json
# Markdown SHA-256:   ca865abc85f70fa0833b6c2cff276ad48b5e95d521365607098a500e252cd8a9
# Code AST SHA-256:   621165ba85ef3bb4e08c5b69d8c4e67c6e6b4bf9f366df4afbb7327042f652d3
# Verified Classes:   StaleDelegationChainError, Capability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleDelegationChainError(RuntimeError):
    """Raised when a terminal capability's stamped revocation epoch is too far
    behind the verifier's current epoch, indicating a chain that may have
    outlived an ancestor's revocation horizon."""
    pass


@dataclass(frozen=True)
class Capability:
    token_id: str
    root_id: str
    stamped_epoch: int      # revocation sequence number observed at attenuation
    chain_depth: int


def verify_terminal_capability(
    cap: Capability,
    current_epoch: int,
    max_acceptable_lag: int,
    chain_latency_s: float,
    min_refresh_period_s: float,
) -> None:
    # The shadow only exists when chain latency can exceed the refresh period.
    shadow_possible = chain_latency_s > min_refresh_period_s

    lag = current_epoch - cap.stamped_epoch

    if lag < 0:
        raise StaleDelegationChainError(
            f"token {cap.token_id} stamped epoch {cap.stamped_epoch} is ahead of "
            f"verifier epoch {current_epoch}; clock or log divergence"
        )

    if lag > max_acceptable_lag:
        raise StaleDelegationChainError(
            f"token {cap.token_id} (root={cap.root_id}, depth={cap.chain_depth}) "
            f"stamped epoch lag {lag} exceeds bound {max_acceptable_lag}; "
            f"ancestor revocation may have occurred within the shadow "
            f"(chain_latency={chain_latency_s}s, shadow_possible={shadow_possible})"
        )

    # If we get here, the chain is within the bounded lag and may proceed.
    return None
