# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-when-a-scoped-capability-token-s-attenuation-chain-diverges-from-the-issuer-s-live-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-when-a-scoped-capability-token-s-attenuation-chain-diverges-from-the-issuer-s-live-revocation-epoch.warrant.json
# Markdown SHA-256:   a9309a7e8b5fd63c84cf4897e546776447dd0e4a7dacc6ef9e7b53dba8965973
# Code AST SHA-256:   ddb817cc08f73f1f7dd522e592eaaeddd0579a6d0e42382b58e7bc310764102e
# Verified Classes:   EpochStaleError, IssuerUnreachableError, CapabilityToken, RootState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochStaleError(RuntimeError):
    """Raised when a delegated token's revocation-epoch binding is older than
    the root issuer's current epoch, or older than the allowed staleness window.
    This is a TERMINAL error: retrying from the same epoch cannot succeed."""


class IssuerUnreachableError(RuntimeError):
    """Transient: the root could not be polled. Distinct from EpochStaleError
    so callers do not conflate a semantic rejection with a transport failure."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: frozenset
    rev_epoch: int
    nbf: float
    exp: float
    chain_depth: int


@dataclass(frozen=True)
class RootState:
    rev_epoch: int
    observed_at: float


MAX_EPOCH_STALENESS = 300.0  # seconds; MUST be < min token lifetime in chain


def _poll_root(root_client) -> RootState:
    try:
        epoch = root_client.current_rev_epoch()
    except TimeoutError as exc:
        raise IssuerUnreachableError("root issuer did not respond") from exc
    return RootState(rev_epoch=epoch, observed_at=time.time())


def assert_chain_current(
    token: CapabilityToken,
    root_client,
    now: float | None = None,
) -> RootState:
    """Enforce the epoch invariant before any action or re-delegation.

    Invariant: token.rev_epoch >= root.rev_epoch AND the root observation is
    fresh. Structural and temporal validity are assumed already checked.
    """
    now = now if now is not None else time.time()

    # Temporal validity is necessary but not the failure we are guarding.
    if not (token.nbf <= now <= token.exp):
        raise EpochStaleError(
            f"token for {token.subject} outside temporal window"
        )

    # The token's lifetime must not exceed the staleness budget, or the
    # offline-verified regime is unsound for this token by construction.
    if (token.exp - token.nbf) > MAX_EPOCH_STALENESS:
        raise EpochStaleError(
            f"token lifetime {token.exp - token.nbf:.0f}s exceeds "
            f"max_epoch_staleness {MAX_EPOCH_STALENESS:.0f}s; "
            "chain requires online attestation"
        )

    root = _poll_root(root_client)

    if (now - root.observed_at) > MAX_EPOCH_STALENESS:
        # Defensive: _poll_root should always return fresh, but a cached
        # RootState passed in by a caller could violate this.
        raise EpochStaleError("root observation is stale")

    if token.rev_epoch < root.rev_epoch:
        raise EpochStaleError(
            f"token epoch {token.rev_epoch} < root epoch {root.rev_epoch}; "
            f"chain for {token.subject} at depth {token.chain_depth} "
            "was superseded and must be re-attested from the root"
        )

    return root


def mint_child(
    parent: CapabilityToken,
    narrowed_scope: frozenset,
    lifetime_s: float,
    root_client,
) -> CapabilityToken:
    """Mint an attenuated child. Refuses to mint from a stale epoch."""
    if not narrowed_scope.issubset(parent.scope):
        raise ValueError("attenuation may only narrow scope, never widen")

    if lifetime_s > MAX_EPOCH_STALENESS:
        raise EpochStaleError(
            f"requested lifetime {lifetime_s:.0f}s exceeds staleness budget; "
            "child would be silently revocable"
        )

    root = assert_chain_current(parent, root_client)

    return CapabilityToken(
        subject=f"{parent.subject}/child",
        scope=narrowed_scope,
        rev_epoch=root.rev_epoch,      # bind to the FRESH epoch, not parent's
        nbf=time.time(),
        exp=time.time() + lifetime_s,
        chain_depth=parent.chain_depth + 1,
    )
