# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-delegated-aaif-capability-token-whose-scope-narrowing-chain-is-valid-at-every-hop-but-whose-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-delegated-aaif-capability-token-whose-scope-narrowing-chain-is-valid-at-every-hop-but-whose-a.warrant.json
# Markdown SHA-256:   c6df4d88d48f724ccfaf1d33601433dbce359f6344003c54fe9d7fb69b1598a9
# Code AST SHA-256:   b4e775f8279913044cd854132551e8f6dba6ece28828fb05b18ec79875e74396
# Verified Classes:   DelegationChainScopeViolation, Hop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, FrozenSet

class DelegationChainScopeViolation(RuntimeError):
    """Raised when a pairwise-valid delegation chain exceeds root grant scope."""

@dataclass(frozen=True)
class Hop:
    subject: str
    raw_scope: FrozenSet[str]
    normalizer_id: str

def authorize_chain(
    chain: list[Hop],
    root_grant: FrozenSet[str],
    root_normalizer_id: str,
    normalizers: dict[str, Callable[[FrozenSet[str]], FrozenSet[str]]],
    max_depth: int = 1,
) -> FrozenSet[str]:
    if len(chain) > max_depth:
        raise DelegationChainScopeViolation(
            f"chain depth {len(chain)} exceeds root max_delegation_depth {max_depth}"
        )
    root_norm = normalizers.get(root_normalizer_id)
    if root_norm is None:
        raise DelegationChainScopeViolation(
            f"root normalizer {root_normalizer_id!r} unavailable; cannot verify global containment"
        )

    # Pairwise edge check (necessary, not sufficient).
    for parent, child in zip(chain, chain[1:]):
        if not child.raw_scope <= parent.raw_scope:
            raise DelegationChainScopeViolation(
                f"edge {parent.subject}->{child.subject} violates pairwise subset"
            )

    effective = chain[0].raw_scope
    for hop in chain[1:]:
        norm = normalizers.get(hop.normalizer_id)
        if norm is None:
            raise DelegationChainScopeViolation(
                f"hop {hop.subject} normalizer {hop.normalizer_id!r} unavailable"
            )
        effective = effective & norm(hop.raw_scope)

    root_scope = root_norm(root_grant)
    leaked = root_norm(effective) - root_scope
    if leaked:
        raise DelegationChainScopeViolation(
            f"effective scope exceeds root grant; leaked={sorted(leaked)}"
        )
    return root_norm(effective)
