# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-valid-aaif-delegated-capability-token-despite-a-passing-signature-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-valid-aaif-delegated-capability-token-despite-a-passing-signature-chain.warrant.json
# Markdown SHA-256:   43dea95c4102159ce37a9cacefe3f52796541f33de286a538741f22435a807d0
# Code AST SHA-256:   c623a5254f42d30060b0ccc207545bb3c4bdde856317d54ecf4a5b1063f229d1
# Verified Classes:   DelegationAttenuationError, DelegationLink, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationAttenuationError(RuntimeError):
    """Raised when a delegated capability token is structurally valid but
    semantically unauthorized: the delegation chain is not monotonically
    attenuating, or a required constraint claim is missing."""
    pass


@dataclass
class DelegationLink:
    parent_capability_set: frozenset
    capability_set: frozenset
    delegation_depth: int


@dataclass
class CapabilityToken:
    audience: str
    delegate_chain: list
    signature_valid: bool
    max_delegation_depth: int


REQUIRED_CONSTRAINT_CLAIMS = frozenset({"resource_prefix", "time_window"})


def verify_delegated_token(
    token: CapabilityToken,
    verifier_did: str,
    present_claims: frozenset,
) -> bool:
    # Stage 1: structural verification.
    if not token.signature_valid:
        raise DelegationAttenuationError("signature chain failed verification")
    if token.audience != verifier_did:
        raise DelegationAttenuationError(
            f"audience mismatch: token for {token.audience!r}, verifier {verifier_did!r}"
        )

    # Stage 2: semantic verification. Do NOT short-circuit on stage 1.
    missing = REQUIRED_CONSTRAINT_CLAIMS - present_claims
    if missing:
        # Fail closed: absence of a constraint claim is not "unconstrained".
        raise DelegationAttenuationError(
            f"required constraint claims absent: {sorted(missing)}"
        )

    for index, link in enumerate(token.delegate_chain):
        if not link.capability_set <= link.parent_capability_set:
            widened = link.capability_set - link.parent_capability_set
            raise DelegationAttenuationError(
                f"non-attenuating delegation at link {index}: widened by {sorted(widened)}"
            )
        if link.delegation_depth > token.max_delegation_depth:
            raise DelegationAttenuationError(
                f"delegation depth {link.delegation_depth} exceeds max "
                f"{token.max_delegation_depth} at link {index}"
            )
        if index > 0:
            prev_depth = token.delegate_chain[index - 1].delegation_depth
            if link.delegation_depth < prev_depth:
                raise DelegationAttenuationError(
                    f"delegation depth reset at link {index}: "
                    f"{prev_depth} -> {link.delegation_depth}"
                )

    return True
