# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegation-chain-depth-overflow-is-silently-collapsing-scope-in-aaif-scoped-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegation-chain-depth-overflow-is-silently-collapsing-scope-in-aaif-scoped-capability-tokens.warrant.json
# Markdown SHA-256:   237106db4475d0e0ff8abd3129f311d3d39f13ec0f1c4f53d6aa8f1be0aa12e3
# Code AST SHA-256:   a9229924a27f2cab0018db392c7649f3b8b59ba634fcf5958a423a941342494e
# Verified Classes:   ScopeCollapse, ScopeAttenuationWarning, Scope, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ScopeCollapse(RuntimeError):
    """Raised when a delegation hop would mint a zero-cardinality capability token."""


class ScopeAttenuationWarning(RuntimeWarning):
    """Raised when a hop attenuates scope by more than the configured ratio."""


@dataclass
class Scope:
    resources: frozenset[str]

    def intersect(self, other: "Scope") -> "Scope":
        # Intersection over denoted resource sets, NOT token strings.
        return Scope(self.resources & other.resources)

    def cardinality(self) -> int:
        return len(self.resources)


@dataclass
class CapabilityToken:
    issuer: str
    subject: str
    scope: Scope
    attenuation_depth: int = 0
    parent_scopes: list[Scope] = field(default_factory=list)


def delegate(
    parent: CapabilityToken,
    subject: str,
    requested: Scope,
    collapse_ratio: float = 0.90,
) -> CapabilityToken:
    effective = parent.scope.intersect(requested)
    depth = parent.attenuation_depth + 1

    if effective.cardinality() == 0:
        # Silent collapse boundary: never mint a zero-cardinality token.
        raise ScopeCollapse(
            f"delegation {parent.subject}->{subject} at depth {depth} "
            f"produced empty scope; parent={sorted(parent.scope.resources)} "
            f"requested={sorted(requested.resources)}"
        )

    if parent.scope.cardinality() > 0:
        loss = 1.0 - (effective.cardinality() / parent.scope.cardinality())
        if loss > collapse_ratio:
            raise ScopeAttenuationWarning(
                f"hop {parent.subject}->{subject} attenuated {loss:.0%} of scope; "
                f"likely vocabulary mismatch, will collapse next hop"
            )

    return CapabilityToken(
        issuer=parent.subject,
        subject=subject,
        scope=effective,
        attenuation_depth=depth,
        parent_scopes=parent.parent_scopes + [parent.scope],
    )


def validate_chain(token: CapabilityToken) -> None:
    # Invariant guard for tokens received from an external AAIF minter.
    if token.attenuation_depth > 1 and token.scope.cardinality() == 0:
        raise ScopeCollapse(
            f"received collapsed token {token.issuer}->{token.subject} "
            f"depth={token.attenuation_depth} cardinality=0"
        )
