# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-authority-chain-at-a-federation-trust-anchor-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-authority-chain-at-a-federation-trust-anchor-boundary.warrant.json
# Markdown SHA-256:   b447d9ffd87882d2f3304d76130543417142fc7c1f4db106f48f6c493c9a7ad4
# Code AST SHA-256:   c951a1a97d074501aeed4f91a152711c87cc9a0df7bdb7b6b664fa7c6f358eb4
# Verified Classes:   AnchorAdmissibilityError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class AnchorAdmissibilityError(RuntimeError):
    """Raised when a delegated warrant's terminal anchor is not trusted
    for the leaf capability class, even though the chain verifies."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    anchor: str          # terminal root this warrant claims
    capability: str      # leaf capability class, e.g. "data:read:public"
    scope: FrozenSet[str]
    depth: int


def admit_delegated_warrant(
    chain: list[Warrant],
    *,
    trusted_anchors_for: Mapping[tuple[str, str], int],  # (anchor, cap_class) -> max_depth
    local_anchor: str,
) -> Warrant:
    if not chain:
        raise AnchorAdmissibilityError("empty delegation chain")

    leaf = chain[-1]

    # (a) signature verification is assumed upstream; (b) scope subset across chain.
    for parent, child in zip(chain, chain[1:]):
        if not child.scope <= parent.scope:
            raise AnchorAdmissibilityError(
                f"scope escalation: {child.scope} !<= {parent.scope}"
            )

    # Re-root detection: terminal anchor must match every link's claimed anchor,
    # otherwise an intermediate substituted its own root.
    terminal = leaf.anchor
    for link in chain:
        if link.anchor != terminal:
            raise AnchorAdmissibilityError(
                f"anchor re-root detected: link {link.issuer} claims {link.anchor}, "
                f"terminal is {terminal}"
            )

    # (c) capability-scoped anchor admissibility — the boundary that failed.
    cap_class = leaf.capability
    key = (terminal, cap_class)
    if key not in trusted_anchors_for:
        raise AnchorAdmissibilityError(
            f"anchor {terminal} is not trusted for capability class {cap_class!r}; "
            f"identity-level trust is insufficient"
        )

    max_depth = trusted_anchors_for[key]
    if leaf.depth > max_depth:
        raise AnchorAdmissibilityError(
            f"delegation depth {leaf.depth} exceeds anchor {terminal} cap {max_depth} "
            f"for {cap_class!r}"
        )

    return leaf
