# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-depth-exceeds-the-issuing-policy-s-max-hop-and-whose-intermedia.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-depth-exceeds-the-issuing-policy-s-max-hop-and-whose-intermedia.warrant.json
# Markdown SHA-256:   353ae4616e84a1684bed02aedace6c6c18a9ec13288e218bbb7ed5f487127495
# Code AST SHA-256:   6a2ee4407fe536e4d9320722a3485bda30a2845b318504020c27707ae3c6d747
# Verified Classes:   DelegationDepthViolation, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationDepthViolation(RuntimeError):
    """Raised when a delegated AAIF warrant chain exceeds or misreports its depth budget."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    depth: int
    max_hop: int
    scope: frozenset
    narrowing_depth: Optional[int] = None  # depth_at_narrowing if this hop re-signed after narrowing


def verify_delegation_chain(chain: list[Warrant], root_max_hop: int) -> Warrant:
    if not chain:
        raise DelegationDepthViolation("empty warrant chain")
    root = chain[0]
    if root.max_hop != root_max_hop:
        raise DelegationDepthViolation(
            f"root max_hop {root.max_hop} disagrees with trusted root budget {root_max_hop}"
        )
    derived = 0
    for i, w in enumerate(chain):
        if w.max_hop != root_max_hop:
            raise DelegationDepthViolation(
                f"hop {i} ({w.issuer}) advertises max_hop={w.max_hop}, "
                f"root budget is {root_max_hop} — template-copy re-sign suspected"
            )
        if i > 0 and w.issuer != chain[i - 1].subject:
            raise DelegationDepthViolation(
                f"hop {i} issuer {w.issuer} does not match prior subject {chain[i - 1].subject}"
            )
        if w.depth != derived:
            raise DelegationDepthViolation(
                f"hop {i} declares depth={w.depth}, derived depth={derived} — "
                f"counter reset across re-sign"
            )
        if w.narrowing_depth is not None and w.narrowing_depth != derived:
            raise DelegationDepthViolation(
                f"hop {i} narrowing recorded at depth {w.narrowing_depth}, "
                f"actual depth {derived}"
            )
        derived += 1
    if derived - 1 > root_max_hop:
        raise DelegationDepthViolation(
            f"derived hops {derived - 1} exceed root max_hop {root_max_hop}"
        )
    return chain[-1]
