# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-it-can-cryptographically-verify-the-delegation-depth-scope-amplification-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-it-can-cryptographically-verify-the-delegation-depth-scope-amplification-invariant.warrant.json
# Markdown SHA-256:   364fa08d2d469edafdf6c9a496904245ac00418c4e025bb4f774146831aa1432
# Code AST SHA-256:   39f6b797a6f3e843f40ff59110bb86f94de4d293561293bddf00967571956109
# Verified Classes:   DelegationScopeViolation, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationScopeViolation(RuntimeError):
    """Raised when an AAIF delegation chain violates scope attenuation,
    depth bounds, or carries an unclassifiable scope token."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str
    issuer: str
    granted_scopes: FrozenSet[str]
    max_delegation_depth: int
    expires_at: int
    parent_hash: str | None
    declared_effective_scopes: FrozenSet[str] | None = None


KNOWN_SCOPE_PREFIXES = ("read:", "write:", "admin:")


def _normalize(scopes: FrozenSet[str]) -> FrozenSet[str]:
    out = set()
    for s in scopes:
        if not any(s.startswith(p) for p in KNOWN_SCOPE_PREFIXES):
            # Closed-world default: unknown grammar token is not "probably fine".
            raise DelegationScopeViolation(
                f"unclassifiable scope token {s!r}; refusing to interpret"
            )
        out.add(s)
    return frozenset(out)


def verify_chain(chain: list[Credential], now: int) -> FrozenSet[str]:
    """Walk a root-to-leaf AAIF chain and return the effective scope set.
    Raises DelegationScopeViolation on any invariant failure."""
    if not chain:
        raise DelegationScopeViolation("empty delegation chain")

    root = chain[0]
    running = _normalize(root.granted_scopes)
    max_depth = root.max_delegation_depth
    prev_expiry = root.expires_at

    for depth, cred in enumerate(chain[1:], start=1):
        if cred.expires_at > prev_expiry:
            raise DelegationScopeViolation(
                f"hop {depth}: expiry {cred.expires_at} exceeds parent {prev_expiry}"
            )
        if depth > max_depth:
            raise DelegationScopeViolation(
                f"hop {depth}: exceeds max_delegation_depth {max_depth}"
            )
        hop_scopes = _normalize(cred.granted_scopes)
        if not hop_scopes.issubset(running):
            amplified = hop_scopes - running
            raise DelegationScopeViolation(
                f"hop {depth}: scope amplification {sorted(amplified)} "
                f"not granted by ancestor intersection"
            )
        if cred.declared_effective_scopes is not None:
            declared = _normalize(cred.declared_effective_scopes)
            recomputed = hop_scopes & running
            if declared != recomputed:
                raise DelegationScopeViolation(
                    f"hop {depth}: declared effective_scopes {sorted(declared)} "
                    f"!= recomputed {sorted(recomputed)}"
                )
        running = hop_scopes
        max_depth = min(max_depth - 1, cred.max_delegation_depth)
        prev_expiry = cred.expires_at

    return running


def execute_tool(chain: list[Credential], now: int, required: FrozenSet[str]) -> None:
    effective = verify_chain(chain, now)
    missing = _normalize(required) - effective
    if missing:
        raise DelegationScopeViolation(
            f"tool requires {sorted(missing)} not present in effective scope set"
        )
    # ... proceed with execution under `effective` only ...
