# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-tool-call-because-its-warrant-chain-attenuated-below-the-required-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-tool-call-because-its-warrant-chain-attenuated-below-the-required-capability.warrant.json
# Markdown SHA-256:   7459467aa0eaa0003a61b57e5d4bc7c7970be32d3aa1ebe0478783262a30720d
# Code AST SHA-256:   a5ac47803da4abc7e3a0205e6fb3915704691fd2671fdf779a0a85f5421fb03f
# Verified Classes:   AttenuationCollapse, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttenuationCollapse(RuntimeError):
    """Raised when a delegation chain's effective capability no longer
    admits the requested call, even though every individual warrant
    verifies locally."""
    pass


@dataclass
class Warrant:
    scope: frozenset          # empty frozenset means DENY, never inherit
    budget: int               # total tokens granted at this hop
    ttl: float                # absolute expiry timestamp
    delegatee: str
    parent: Optional["Warrant"] = None
    consumed: int = field(default=0)  # tokens spent by this warrant's subtree


def effective_scope(w: Warrant) -> frozenset:
    s = w.scope
    p = w.parent
    while p is not None:
        s = s & p.scope
        p = p.parent
    return s


def remaining_budget(w: Warrant) -> int:
    # Budget is the min over the path of (granted - consumed-by-subtree).
    rem = w.budget - w.consumed
    p = w.parent
    while p is not None:
        rem = min(rem, p.budget - p.consumed)
        p = p.parent
    return rem


def authorize(w: Warrant, op: str, tokens: int, now: float) -> None:
    sc = effective_scope(w)
    if not sc:
        raise AttenuationCollapse(
            f"empty effective scope on chain ending at {w.delegatee}; "
            f"refusing {op!r} rather than inheriting ancestor scope"
        )
    if op not in sc:
        raise AttenuationCollapse(
            f"op {op!r} not in effective scope {sorted(sc)} for {w.delegatee}"
        )
    if now >= w.ttl:
        raise AttenuationCollapse(f"warrant for {w.delegatee} expired")
    rem = remaining_budget(w)
    if tokens > rem:
        raise AttenuationCollapse(
            f"call needs {tokens} tokens but path has {rem} remaining "
            f"(ancestor budget already consumed by siblings)"
        )
    # Charge the whole path so sibling consumption is visible.
    w.consumed += tokens
    p = w.parent
    while p is not None:
        p.consumed += tokens
        p = p.parent


def delegate(parent: Warrant, child_scope: frozenset, budget: int,
             ttl: float, delegatee: str) -> Warrant:
    inter = child_scope & parent.scope
    if not inter:
        raise AttenuationCollapse(
            f"refusing to mint warrant for {delegatee}: scope intersection "
            f"{sorted(child_scope)} & {sorted(parent.scope)} is empty"
        )
    if budget > parent.budget - parent.consumed:
        raise AttenuationCollapse(
            f"refusing to mint warrant for {delegatee}: requested {budget} "
            f"exceeds parent remaining {parent.budget - parent.consumed}"
        )
    return Warrant(scope=inter, budget=budget, ttl=min(ttl, parent.ttl),
                   delegatee=delegatee, parent=parent)
