# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-aaif-delegated-credential-exchange-enforce-scope-attenuation-at-the-token-minting-boundary-rather-than-at-the-relying-party.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-aaif-delegated-credential-exchange-enforce-scope-attenuation-at-the-token-minting-boundary-rather-than-at-the-relying-party.warrant.json
# Markdown SHA-256:   3e04fb44c3ee24242486576ed0a6679f646470b0b9f5700874d9acbc3f6d3b56
# Code AST SHA-256:   d82edf5694c6571de40ccf193d8d0e4741b2641b116b87c0a3b9c909fd40a9d2
# Verified Classes:   ScopeAttenuationError, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated child token would exceed its parent's scope."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scopes: FrozenSet[str]
    max_delegation_depth: int
    signature_valid: bool


def mint_delegated_token(
    parent: CapabilityToken,
    child_subject: str,
    requested_scopes: FrozenSet[str],
) -> CapabilityToken:
    # Condition 1: parent provenance — use the presented token, never a cache.
    if not parent.signature_valid:
        raise ScopeAttenuationError(
            f"parent token for {parent.subject} has invalid signature; refusing to mint"
        )

    # Condition 3: closure under scope algebra — we only support exact scope
    # atoms here. Wildcards/conditions must be decided by a real solver; if the
    # algebra is undecidable at this endpoint, refuse rather than approximate.
    for scope in requested_scopes:
        if "*" in scope or " if " in scope:
            raise ScopeAttenuationError(
                f"scope {scope!r} uses an algebra this endpoint cannot decide; refusing"
            )

    # Condition 2: revocation freshness — the presented parent is authoritative,
    # so a revoked scope simply will not appear in parent.scopes.
    escalation = requested_scopes - parent.scopes
    if escalation:
        raise ScopeAttenuationError(
            f"requested scopes {sorted(escalation)} exceed parent scope "
            f"{sorted(parent.scopes)}; refusing to mint"
        )

    if parent.max_delegation_depth <= 0:
        raise ScopeAttenuationError(
            f"delegation depth exhausted for {parent.subject}; refusing to mint"
        )

    return CapabilityToken(
        subject=child_subject,
        scopes=requested_scopes,
        max_delegation_depth=parent.max_delegation_depth - 1,
        signature_valid=True,
    )
