# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-chain-that-verifies-cryptographically-but-exceeds-its-transitive-capability-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-chain-that-verifies-cryptographically-but-exceeds-its-transitive-capability-budget.warrant.json
# Markdown SHA-256:   387d5d586b372e70e16da3c5a346c4c6b43ff3fe5d8f2db12383ab58812292f4
# Code AST SHA-256:   7d5cda804579e9ab2d5cb9e5f4ae96f84877811027b5362be4f71005b599eb0b
# Verified Classes:   TransitiveAttenuationViolation, Warrant, Hop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class TransitiveAttenuationViolation(RuntimeError):
    """Raised when a chain is signature-valid but escapes the root warrant's scope closure."""


@dataclass(frozen=True)
class Warrant:
    granted_namespaces: FrozenSet[str]   # closed set; anything else is DENIED
    remaining_budget: int
    max_reissuance_depth: int
    not_after: float


@dataclass(frozen=True)
class Hop:
    issuer_domain: str
    granted_namespaces: FrozenSet[str]
    consumed_budget: int
    reissued: bool = field(default=True)


def authorize_terminal(
    root: Optional[Warrant],
    hops: list[Hop],
    now: float,
) -> None:
    # 1. Root warrant must be resolvable at the terminal consumer.
    if root is None:
        raise TransitiveAttenuationViolation(
            "root warrant unresolvable at terminal domain; closure unverifiable -> fail closed"
        )

    # 2. Expiry.
    if now > root.not_after:
        raise TransitiveAttenuationViolation("root warrant expired")

    # 3. Transitive namespace-closure containment against the ROOT, not the parent.
    terminal_scope = hops[-1].granted_namespaces
    escaped = terminal_scope - root.granted_namespaces
    if escaped:
        raise TransitiveAttenuationViolation(
            f"terminal scope escapes root closure: {sorted(escaped)} "
            f"not in root grant {sorted(root.granted_namespaces)}"
        )

    # 4. Monotonic budget: sum consumption across the whole path.
    total_consumed = sum(h.consumed_budget for h in hops)
    if total_consumed > root.remaining_budget:
        raise TransitiveAttenuationViolation(
            f"path consumed {total_consumed} > root budget {root.remaining_budget}"
        )

    # 5. Depth = re-issuance count, not presented-chain length.
    reissuances = sum(1 for h in hops if h.reissued)
    if reissuances > root.max_reissuance_depth:
        raise TransitiveAttenuationViolation(
            f"re-issuance depth {reissuances} exceeds max {root.max_reissuance_depth}"
        )
