# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-aaif-delegated-capability-token-whose-issuer-chain-is-cryptographically-valid-but-whose-delegation-de.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-aaif-delegated-capability-token-whose-issuer-chain-is-cryptographically-valid-but-whose-delegation-de.warrant.json
# Markdown SHA-256:   22b271b4a74a78add3b2c4e96eee2986f962e544a8e14738f736697ac03695d8
# Code AST SHA-256:   fe176ca352dc3e5a58fb360b5501eafc8c1a4006e3107d70f7b2596a4c1a46f3
# Verified Classes:   DelegationDepthExceeded
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class DelegationDepthExceeded(RuntimeError):
    """Raised when an AAIF DCT chain is signature-valid but exceeds the
    verifier's local trust horizon measured from the root anchor."""


def admit_delegated_token(
    token: dict,
    chain: list[dict],
    local_trust_horizon: int,
    local_scope_policy: set[str],
) -> bool:
    # chain is ordered root -> ... -> presenting link; token is chain[-1]
    if not chain:
        raise DelegationDepthExceeded("empty chain: no root to attribute to")

    root = chain[0]
    root_budget = root.get("max_delegation_depth")
    presenting = chain[-1]

    if root_budget is None:
        # Root declared no budget: the chain is depth-unbounded by construction.
        # Refuse rather than admit an unattributable capability.
        raise DelegationDepthExceeded(
            "root anchor declared no max_delegation_depth; cannot bound chain"
        )

    remaining = presenting.get("remaining_depth")
    if remaining is None:
        # Missing depth field on a chain whose root declared a finite budget.
        # Treat as exhaustion: absence is not 'no constraint'.
        raise DelegationDepthExceeded(
            f"presenting link missing remaining_depth; root budget={root_budget}"
        )

    hops_consumed = root_budget - remaining
    if remaining < 0 or hops_consumed > root_budget:
        raise DelegationDepthExceeded(
            f"chain over-consumed root budget: remaining={remaining}, "
            f"root_budget={root_budget}, hops={hops_consumed}"
        )

    if hops_consumed > local_trust_horizon:
        raise DelegationDepthExceeded(
            f"effective_depth={hops_consumed} exceeds local_trust_horizon="
            f"{local_trust_horizon} (root_budget={root_budget})"
        )

    cumulative_scope: set[str] = set()
    for link in chain:
        cumulative_scope |= set(link.get("scope", []))
    if not cumulative_scope.issubset(local_scope_policy):
        # Scope mismatch is a separate, earlier-class failure; surface it
        # distinctly so callers do not confuse it with depth exhaustion.
        raise DelegationDepthExceeded(
            f"cumulative scope {cumulative_scope - local_scope_policy} "
            f"not contained in local policy"
        )

    return True
