# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-capability-token-s-policy-constraints-before-each-a2a-hop-rather-than-trusting-the-upstre.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-capability-token-s-policy-constraints-before-each-a2a-hop-rather-than-trusting-the-upstre.warrant.json
# Markdown SHA-256:   d865aae36166bc97a9390137fbdc076176f4ecf340f33a2a5135f11e3de7ebaf
# Code AST SHA-256:   d94d673a643863f6b92ba7b01505618c7fe99a0bccf9b6423256e533237ff636
# Verified Classes:   CapabilityAttenuationError, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class CapabilityAttenuationError(RuntimeError):
    """Raised when a delegated capability token's cached verdict does not
    cover the (principal, resource, budget, time) tuple of the current hop."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    root_audience_set: FrozenSet[str]   # principals authorized by the ROOT PDP
    resource_pattern: str               # e.g. "proj-88/*"
    remaining_records: int              # BALANCE, not ceiling
    not_after_epoch: float              # absolute deadline
    delegation_depth: int
    delegation_depth_max: int
    delegated_by: str


def authorize_hop(
    token: CapabilityToken,
    principal: str,
    requested_resource: str,
    worst_case_records: int,
    commit_epoch: float,
) -> None:
    """Re-derive or fast-path the policy decision for one A2A hop.

    Raises CapabilityAttenuationError if the cached verdict does not cover
    this hop's tuple. Caller must then re-derive from the root PDP or fail.
    """
    if principal not in token.root_audience_set:
        raise CapabilityAttenuationError(
            f"principal {principal!r} not in root audience_set "
            f"{sorted(token.root_audience_set)}; token was granted to a "
            f"different principal and cannot be re-targeted"
        )

    if token.delegation_depth > token.delegation_depth_max:
        raise CapabilityAttenuationError(
            f"delegation_depth {token.delegation_depth} exceeds max "
            f"{token.delegation_depth_max}"
        )

    if worst_case_records > token.remaining_records:
        raise CapabilityAttenuationError(
            f"hop worst-case {worst_case_records} exceeds remaining balance "
            f"{token.remaining_records}; budget must be decremented, not copied"
        )

    if commit_epoch >= token.not_after_epoch:
        raise CapabilityAttenuationError(
            f"commit at {commit_epoch} is past not_after "
            f"{token.not_after_epoch}; expiry must be checked at commit, "
            f"not at admission"
        )

    # Pattern membership is necessary but not sufficient; caller must still
    # confirm requested_resource is in the root PDP's satisfying set for
    # this principal's entitlements.
    prefix = token.resource_pattern.rstrip("*")
    if not requested_resource.startswith(prefix):
        raise CapabilityAttenuationError(
            f"resource {requested_resource!r} outside filter "
            f"{token.resource_pattern!r}"
        )
