# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-capability-token-as-already-revoked-mid-chain-the-attenuation-revocation-ordering-hazard-in-a2a-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-capability-token-as-already-revoked-mid-chain-the-attenuation-revocation-ordering-hazard-in-a2a-authorization.warrant.json
# Markdown SHA-256:   023a8043091322f4cee7f62eba36764bb189fefd7d935f6046454d8b784c1a38
# Code AST SHA-256:   9896260a0e530d65d38f954886f5f36abc690835682ae3abb44e0a0909e8cf98
# Verified Classes:   StaleCapabilityError, RevokedRootError, Capability, RevocationProbe
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleCapabilityError(RuntimeError):
    """Raised when a delegated token's attenuation chain is valid but its
    revocation freshness cannot be established within the allowed window."""


class RevokedRootError(RuntimeError):
    """Raised when the root grant of a delegated token has been revoked."""


@dataclass
class Capability:
    subject: str
    scope: frozenset
    parent_id: Optional[str]
    root_id: str
    expiry: float
    revoked_at: Optional[float] = None


@dataclass
class RevocationProbe:
    """Tracks the last time the authority was consulted for a given root."""
    root_id: str
    last_probed: Optional[float] = None
    revoked: bool = False
    revoked_at: Optional[float] = None


MAX_STALENESS_SECONDS = 30.0


def validate_and_authorize(
    token: Capability,
    requested_scope: frozenset,
    parent: Optional[Capability],
    probe: RevocationProbe,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # Phase 1: local attenuation validation (necessary, never sufficient).
    if now >= token.expiry:
        raise StaleCapabilityError(f"token expired at {token.expiry}")
    if parent is not None:
        if token.parent_id != parent.root_id and token.parent_id != parent.subject:
            raise StaleCapabilityError("parent linkage mismatch")
        if not requested_scope.issubset(parent.scope):
            raise StaleCapabilityError(
                f"attenuation violation: {requested_scope} not subset of {parent.scope}"
            )
    if not requested_scope.issubset(token.scope):
        raise StaleCapabilityError("requested scope exceeds token scope")

    # Phase 2: freshness of revocation state (the actual boundary).
    if probe.revoked:
        raise RevokedRootError(f"root {probe.root_id} revoked at {probe.revoked_at}")
    if probe.last_probed is None:
        raise StaleCapabilityError(
            f"no revocation probe for root {probe.root_id}; cannot authorize side effects"
        )
    age = now - probe.last_probed
    if age > MAX_STALENESS_SECONDS:
        raise StaleCapabilityError(
            f"revocation probe for {probe.root_id} is {age:.1f}s stale "
            f"(max {MAX_STALENESS_SECONDS}s); refusing side-effecting action"
        )
    # Fresh and unrevoked: safe to act.
    return None


def re_delegate(
    parent: Capability,
    child_scope: frozenset,
    probe: RevocationProbe,
    now: Optional[float] = None,
) -> Capability:
    """Minting a child token MUST re-probe the root, or it propagates a dead grant."""
    now = now if now is not None else time.time()
    if probe.last_probed is None or (now - probe.last_probed) > MAX_STALENESS_SECONDS:
        raise StaleCapabilityError(
            f"refusing to mint child from root {parent.root_id}: revocation state stale"
        )
    if probe.revoked:
        raise RevokedRootError(f"cannot re-delegate from revoked root {parent.root_id}")
    if not child_scope.issubset(parent.scope):
        raise StaleCapabilityError("child scope not subset of parent scope")
    return Capability(
        subject="child",
        scope=child_scope,
        parent_id=parent.subject,
        root_id=parent.root_id,
        expiry=parent.expiry,
    )
