# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-a2a-capability-warrant-whose-agent-card-signature-chain-is-valid-but-whose-delegation-depth-exceeds-the-signi.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-a2a-capability-warrant-whose-agent-card-signature-chain-is-valid-but-whose-delegation-depth-exceeds-the-signi.warrant.json
# Markdown SHA-256:   8e9036727a22d232a3274607f56e38f5287d184a79f187684fb18fc87fbb0fb7
# Code AST SHA-256:   ec387c463184917679f7e37917be9af359d37ca7c3f26935e3af850919eb8c7c
# Verified Classes:   DelegationDepthExceeded, WarrantChainMalformed, Hop
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationDepthExceeded(RuntimeError):
    """Raised when a signature-valid warrant chain exceeds an intermediate hop's delegation budget."""


class WarrantChainMalformed(RuntimeError):
    """Raised when a chain is truncated, unsigned, or self-reports a depth it cannot support."""


@dataclass(frozen=True)
class Hop:
    did: str
    max_delegation_hops: int          # from this hop's signed key policy
    policy_signed: bool = True
    signature_ok: bool = True


def verify_delegation_chain(chain: list[Hop], declared_leaf_depth: int) -> int:
    """
    chain[0] is the root trust anchor; chain[-1] is the leaf presenting the warrant.
    Enforces monotone narrowing of delegation budget and returns the admitted depth.
    """
    if not chain:
        raise WarrantChainMalformed("empty warrant chain")

    # Structural preconditions first: malformed beats policy-denied.
    for i, hop in enumerate(chain):
        if not hop.signature_ok:
            raise WarrantChainMalformed(f"hop {i} ({hop.did}) signature failed")
        if not hop.policy_signed:
            raise WarrantChainMalformed(f"hop {i} ({hop.did}) key policy unsigned; depth unbounded")

    recomputed_depth = len(chain) - 1
    if recomputed_depth != declared_leaf_depth:
        raise WarrantChainMalformed(
            f"declared depth {declared_leaf_depth} != recomputed {recomputed_depth}"
        )

    # Running-minimum budget fold. budget = hops still available from current position.
    budget = chain[0].max_delegation_hops
    for i in range(1, len(chain)):
        budget = min(budget, chain[i - 1].max_delegation_hops) - 1
        if budget < 0:
            binding = chain[i - 1]
            raise DelegationDepthExceeded(
                f"hop {i - 1} ({binding.did}) permits max_delegation_hops="
                f"{binding.max_delegation_hops}; chain needs depth {i} at {chain[i].did}"
            )

    return recomputed_depth


# Incident replay: root generous (5), gateway narrow (1), leaf at depth 3.
incident_chain = [
    Hop("did:a2a:orgA:root", max_delegation_hops=5),
    Hop("did:a2a:orgB:gw", max_delegation_hops=1),
    Hop("did:a2a:orgB:tenant7:orch", max_delegation_hops=5),
    Hop("did:a2a:orgB:tenant7:sub:research", max_delegation_hops=5),
]

# The naive endpoint check the incident verifier used:
assert incident_chain[-1].max_delegation_hops >= 3  # passes; this is the bug

# The correct fold rejects, naming the gateway as the binding hop:
try:
    verify_delegation_chain(incident_chain, declared_leaf_depth=3)
except DelegationDepthExceeded as e:
    assert "did:a2a:orgB:gw" in str(e)
