# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-delegation-chain-has-silently-exceeded-its-transitive-trust-depth-in-cross-org-agent-federati.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-delegation-chain-has-silently-exceeded-its-transitive-trust-depth-in-cross-org-agent-federati.warrant.json
# Markdown SHA-256:   2287e33a219ceb8d1df28f7ea80a5548d9e6eba51572a59eec2d23323855d64d
# Code AST SHA-256:   7f2f69cd2819c1593f2dd1229b88830cdc727f85708cb1ece69ce7a2de49da8d
# Verified Classes:   DelegationDepthExceeded, RootPolicyUnreachable, Credential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthExceeded(RuntimeError):
    """Raised when a VC delegation chain exceeds the root's maxDepth."""
    pass


class RootPolicyUnreachable(RuntimeError):
    """Raised when the root VC cannot be fetched or cached for depth check."""
    pass


@dataclass
class Credential:
    issuer: str
    subject_agent: str
    scope: frozenset
    delegated_from: "Credential | None"
    verification_method: str
    max_depth: int | None = None  # set only on the root


def compute_depth(cred: Credential) -> int:
    depth = 0
    node = cred
    while node.delegated_from is not None:
        depth += 1
        node = node.delegated_from
    return depth


def verify_delegation_chain(cred: Credential, root_cache: dict) -> bool:
    # Walk to root; do not trust any self-reported depth field.
    node = cred
    while node.delegated_from is not None:
        node = node.delegated_from
    root = node

    # Root must be re-validated or present in a policy cache that carries maxDepth.
    if root.max_depth is None:
        cached = root_cache.get(root.issuer)
        if cached is None or cached.get("maxDepth") is None:
            raise RootPolicyUnreachable(
                f"root issuer {root.issuer} unreachable and no cached maxDepth; "
                f"cannot bound transitive delegation"
            )
        root_max = cached["maxDepth"]
    else:
        root_max = root.max_depth

    depth = compute_depth(cred)
    if depth > root_max:
        raise DelegationDepthExceeded(
            f"delegation depth {depth} exceeds root maxDepth {root_max} "
            f"for issuer {root.issuer}; chain is over-extended"
        )

    # Same verification_method across consecutive links is a depth-consuming hop.
    # Scope must narrow OR depth must be within a decremented budget; here we
    # enforce the conservative rule: unchanged scope across a hop is allowed
    # only if depth is within bound (already checked above).
    return True
