# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-scope-was-widened-by-an-intermediate-agent-the-attenuation-laundering-boundary-in-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-scope-was-widened-by-an-intermediate-agent-the-attenuation-laundering-boundary-in-aaif.warrant.json
# Markdown SHA-256:   12763a6b8be2883bfeac6d74d311c99c681ba6d21e353e70f94183ed9eccdd9d
# Code AST SHA-256:   766305cc54008707a0caa8af9d342c06f22b10a483241b0ecf2e886440fbbba7
# Verified Classes:   CapabilityAttenuationError, ScopeSegment, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityAttenuationError(RuntimeError):
    """Raised when a delegated AAIF token widens scope or depth relative to its parent."""


@dataclass(frozen=True)
class ScopeSegment:
    resource: str
    action: str
    target: str  # concrete id or "*" for wildcard

    def is_subset_of(self, other: "ScopeSegment") -> bool:
        # A concrete target is a subset of a wildcard; a wildcard is NOT a subset of a concrete.
        if self.resource != other.resource or self.action != other.action:
            return False
        if other.target == "*":
            return True
        return self.target == other.target


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    scope: FrozenSet[ScopeSegment]
    depth: int
    max_depth: int
    attenuation_only: bool
    parent_id: str | None = None


def verify_attenuation_chain(chain: list[CapabilityToken]) -> None:
    """
    Enforce the AAIF monotonicity invariant across a delegation chain ordered
    root -> ... -> leaf. Signatures are assumed already verified elsewhere;
    this function checks entitlement, not provenance.
    """
    if not chain:
        raise CapabilityAttenuationError("empty capability chain cannot be verified")

    root = chain[0]
    if root.depth != 0:
        raise CapabilityAttenuationError(
            f"root token {root.token_id} has depth {root.depth}, expected 0"
        )

    for parent, child in zip(chain, chain[1:]):
        if child.depth != parent.depth + 1:
            raise CapabilityAttenuationError(
                f"depth discontinuity {parent.token_id}->{child.token_id}: "
                f"{parent.depth}->{child.depth}"
            )
        if child.depth > root.max_depth:
            raise CapabilityAttenuationError(
                f"token {child.token_id} exceeds root max_depth {root.max_depth}"
            )

        # Every child segment must be covered by some parent segment.
        for seg in child.scope:
            if not any(seg.is_subset_of(p) for p in parent.scope):
                raise CapabilityAttenuationError(
                    f"scope widening at hop {parent.token_id}->{child.token_id}: "
                    f"segment {seg} not covered by parent scope"
                )

        # Wildcard introduction is widening even if nominally covered.
        parent_has_wildcard = any(p.target == "*" for p in parent.scope)
        child_has_wildcard = any(c.target == "*" for c in child.scope)
        if child_has_wildcard and not parent_has_wildcard:
            raise CapabilityAttenuationError(
                f"wildcard introduced at hop {parent.token_id}->{child.token_id} "
                f"despite attenuation_only={parent.attenuation_only}"
            )


def admit_token(chain: list[CapabilityToken], requested: ScopeSegment) -> bool:
    verify_attenuation_chain(chain)
    leaf = chain[-1]
    if not any(requested.is_subset_of(s) for s in leaf.scope):
        # Legitimate out-of-scope request against a sound chain: deny, do not raise.
        return False
    return True
