# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-token-whose-revocation-epoch-is-ahead-of-its-own-clock.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-token-whose-revocation-epoch-is-ahead-of-its-own-clock.warrant.json
# Markdown SHA-256:   2730a21fc72024064d1946b730f28c2a0e214fe54a4ecb2df0f312cac66a652d
# Code AST SHA-256:   c9d3f0cd052900916458994586a257b4d8eccd60184451331623e9b2fca31af0
# Verified Classes:   EpochAheadOfLocal, StaleEpochReplay, PropagationBoundExceeded, CapabilityToken, VerifierState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochAheadOfLocal(RuntimeError):
    """Raised when a delegated PCT claims a revocation epoch the verifier has not synced."""
    pass


class StaleEpochReplay(RuntimeError):
    """Raised when a PCT's epoch is behind local state without a valid freshness nonce."""
    pass


class PropagationBoundExceeded(RuntimeError):
    """Raised when synchronous epoch sync exceeds the token's propagation_bound_ms."""
    pass


@dataclass
class CapabilityToken:
    issuer: str
    issuer_epoch: int
    counter: int
    propagation_bound_ms: int
    inclusion_proof: bytes


@dataclass
class VerifierState:
    issuer: str
    local_epoch: int
    head_epoch: int
    accumulator: dict


def sync_epoch(state: VerifierState, target: int) -> VerifierState:
    # Placeholder for a real delta sync against the issuer's signed log.
    return VerifierState(
        issuer=state.issuer,
        local_epoch=target,
        head_epoch=max(state.head_epoch, target),
        accumulator=state.accumulator,
    )


def verify_inclusion(token: CapabilityToken, state: VerifierState) -> bool:
    # Placeholder: real check walks the accumulator against token.inclusion_proof.
    return token.counter not in state.accumulator.get("revoked_counters", set())


def authorize(token: CapabilityToken, state: VerifierState) -> bool:
    if token.issuer != state.issuer:
        raise EpochAheadOfLocal(f"issuer mismatch: {token.issuer} vs {state.issuer}")

    if token.issuer_epoch < state.local_epoch:
        raise StaleEpochReplay(
            f"token epoch {token.issuer_epoch} behind local {state.local_epoch}; "
            "requires freshness nonce bound to current window"
        )

    if token.issuer_epoch == state.local_epoch:
        if not verify_inclusion(token, state):
            return False
        return True

    if token.issuer_epoch == state.local_epoch + 1 and state.head_epoch >= token.issuer_epoch:
        start = time.monotonic()
        synced = sync_epoch(state, token.issuer_epoch)
        elapsed_ms = (time.monotonic() - start) * 1000.0
        if elapsed_ms > token.propagation_bound_ms:
            raise PropagationBoundExceeded(
                f"sync took {elapsed_ms:.1f}ms > bound {token.propagation_bound_ms}ms"
            )
        if not verify_inclusion(token, synced):
            return False
        return True

    raise EpochAheadOfLocal(
        f"token epoch {token.issuer_epoch} ahead of local {state.local_epoch} "
        f"(head {state.head_epoch}); defer, do not accept"
    )
