# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-credential-whose-issuer-chain-verifies-but-whose-delegation-depth-was-silently-truncated-by-a-caching-res.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-credential-whose-issuer-chain-verifies-but-whose-delegation-depth-was-silently-truncated-by-a-caching-res.warrant.json
# Markdown SHA-256:   fafad324277a0071940ed414ca7a9aa3e2750d8e19ca79de23d913cf4860b5ad
# Code AST SHA-256:   b31f037e03016c5333dbc9ca5a9c8e7f3acfba02485cd358559c505ed24c1a65
# Verified Classes:   DelegationDepthViolation, ChainLink
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationDepthViolation(RuntimeError):
    """Raised when a resolved chain's recomputed depth exceeds an issuer's bound,
    or when resolver-reported depth disagrees with the signed-claim recomputation."""
    pass


@dataclass(frozen=True)
class ChainLink:
    issuer_did: str
    delegation_depth_claim: int   # signed: max further delegations this issuer permits
    parent_chain_digest: str      # signed: binds this link to its specific parent chain


def verify_delegated_chain(
    links: list[ChainLink],
    resolver_reported_depth: Optional[int],
    trusted_root_did: str,
) -> int:
    """Recompute delegation depth from signed claims only.

    resolver_reported_depth is accepted for divergence detection but is NEVER
    used as the authority for the bound check.
    """
    if not links:
        raise DelegationDepthViolation("empty chain: no signed links to verify")

    if links[0].issuer_did != trusted_root_did:
        raise DelegationDepthViolation(
            f"chain does not anchor to trusted root {trusted_root_did!r}; "
            f"got {links[0].issuer_did!r}"
        )

    # Recompute consumed depth from signed claims: each link consumes one hop
    # of its parent's budget. Hop 0 is the root anchor (consumes nothing).
    consumed = 0
    for i, link in enumerate(links[1:], start=1):
        parent = links[i - 1]
        consumed += 1
        if consumed > parent.delegation_depth_claim:
            raise DelegationDepthViolation(
                f"hop {i} ({link.issuer_did}) consumes depth {consumed}, "
                f"exceeding parent {parent.issuer_did} bound "
                f"{parent.delegation_depth_claim}"
            )
        # Chain integrity: each link must bind to its parent's digest.
        if link.parent_chain_digest != _digest(parent):
            raise DelegationDepthViolation(
                f"hop {i} parent_chain_digest mismatch: chain was spliced or "
                f"truncated relative to signed claims"
            )

    # Divergence detection: a resolver reporting a different depth than the
    # signed claims imply is a truncation signal, not a benign cache hit.
    if resolver_reported_depth is not None and resolver_reported_depth != consumed:
        raise DelegationDepthViolation(
            f"resolver reported depth {resolver_reported_depth} but signed "
            f"claims recompute to {consumed}: cache-key truncation suspected, "
            f"reject and re-resolve with full chain digest"
        )

    return consumed


def _digest(link: ChainLink) -> str:
    # Placeholder for canonical serialization digest of the link's signed body.
    return f"digest::{link.issuer_did}::{link.delegation_depth_claim}"
