# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-aaif-chain-length-exceeds-the-issuer-s-declared-max-delegation-depth-when-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-aaif-chain-length-exceeds-the-issuer-s-declared-max-delegation-depth-when-the.warrant.json
# Markdown SHA-256:   206352f6f5918596c7ae01288d3c31964a19d71ceea0ca07fcc6da8013f1ee6b
# Code AST SHA-256:   2fdd7cb4c00e05c189e767de8fec2120e968c6816b753571693cb989c5328f95
# Verified Classes:   WarrantAdmissibilityError, Warrant
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantAdmissibilityError(RuntimeError):
    """Raised when a delegated AAIF warrant cannot be admitted."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    parent_hash: Optional[str]
    depth_claim: int
    may_delegate: bool
    signature_valid: bool
    root_constraint: Optional[int] = None  # only set on the root attestation


def admit_warrant(
    leaf: Warrant,
    chain: list[Warrant],
    pinned_root_issuer: str,
) -> None:
    """
    Enforce AAIF chain admissibility. chain is ordered root-first, leaf-last.
    Raises WarrantAdmissibilityError on any violated invariant.
    """
    if not chain:
        raise WarrantAdmissibilityError("empty warrant chain")

    root = chain[0]
    if root.issuer != pinned_root_issuer:
        raise WarrantAdmissibilityError(
            f"root issuer {root.issuer!r} not pinned ({pinned_root_issuer!r})"
        )
    if root.root_constraint is None:
        raise WarrantAdmissibilityError("root attestation missing max_delegation_depth")

    # Recompute depth from the walk; never trust leaf.depth_claim.
    recomputed_depth = len(chain) - 1
    if recomputed_depth > root.root_constraint:
        raise WarrantAdmissibilityError(
            f"chain depth {recomputed_depth} exceeds root bound "
            f"{root.root_constraint} (leaf claimed {leaf.depth_claim})"
        )

    # Every link must be signature-valid and parent_hash-consistent.
    for parent, child in zip(chain, chain[1:]):
        if not child.signature_valid:
            raise WarrantAdmissibilityError(
                f"invalid signature at depth {chain.index(child)}"
            )
        # parent_hash binding is checked by the caller against the token bytes;
        # here we assert scope monotonicity and delegation rights.
        if not child.scope <= parent.scope:
            raise WarrantAdmissibilityError(
                f"scope escalation at depth {chain.index(child)}"
            )
        if not parent.may_delegate:
            raise WarrantAdmissibilityError(
                f"parent at depth {chain.index(parent)} lacks may_delegate"
            )

    if leaf is not chain[-1]:
        raise WarrantAdmissibilityError("leaf is not the terminal chain element")
    if leaf.depth_claim != recomputed_depth:
        raise WarrantAdmissibilityError(
            f"depth_claim {leaf.depth_claim} disagrees with recomputed {recomputed_depth}"
        )
