# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-scope-validity-at-the-second-hop-credential-chain-depth-truncation-in-aaif-verifiable-credentials.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-scope-validity-at-the-second-hop-credential-chain-depth-truncation-in-aaif-verifiable-credentials.warrant.json
# Markdown SHA-256:   389f31a0daeeb1d95758474fce2646c3f6ead4670e499909e2ba120bfe6bce4a
# Code AST SHA-256:   89ac8aea277c62f239818f98eec6a72a6f4c11102f971db4ebac0a4d3b858498
# Verified Classes:   DelegationChainError, DelegationLink, VerifiableCredential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when an AAIF delegation chain cannot be validated to a trusted root."""


@dataclass
class DelegationLink:
    issuer: str
    delegatee: str
    scopes: frozenset
    parent_depth: int
    signature_valid: bool = True


@dataclass
class VerifiableCredential:
    root_issuer: str
    root_scopes: frozenset
    signed_chain_depth: int
    links: list = field(default_factory=list)  # ordered presenter -> root


def verify_delegated_scope(
    vc: VerifiableCredential,
    presenter: str,
    requested_scope: str,
    trusted_roots: set,
    max_chain_depth: int = 5,
) -> bool:
    # Invariant 1: depth is signed at the root; observed link count must match.
    observed_depth = len(vc.links) + 1  # links + root
    if observed_depth != vc.signed_chain_depth:
        raise DelegationChainError(
            f"chain depth mismatch for presenter {presenter}: "
            f"signed={vc.signed_chain_depth} observed={observed_depth} "
            f"(possible link-drop or truncation)"
        )

    # Invariant 2: depth cap is a rejection condition, never a truncation point.
    if observed_depth > max_chain_depth:
        raise DelegationChainError(
            f"chain depth {observed_depth} exceeds cap {max_chain_depth} "
            f"for presenter {presenter}; refusing to validate truncated suffix"
        )

    # Walk presenter -> root, intersecting scopes; must reach a trusted root.
    effective = frozenset({requested_scope})
    prev_delegatee: Optional[str] = presenter
    for link in vc.links:
        if not link.signature_valid:
            raise DelegationChainError(f"invalid signature on link {link.issuer}->{link.delegatee}")
        if link.delegatee != prev_delegatee:
            raise DelegationChainError(
                f"broken chain: link delegatee {link.delegatee} != expected {prev_delegatee}"
            )
        if link.parent_depth + 1 != (vc.signed_chain_depth - vc.links.index(link)):
            raise DelegationChainError(f"depth accounting error at link {link.issuer}")
        effective = effective & link.scopes
        prev_delegatee = link.issuer

    if vc.root_issuer not in trusted_roots:
        raise DelegationChainError(
            f"walk terminated at {vc.root_issuer}, not a trusted root; "
            f"cannot validate scope for {presenter}"
        )
    if prev_delegatee != vc.root_issuer:
        raise DelegationChainError("chain did not terminate at the root issuer")

    effective = effective & vc.root_scopes
    return requested_scope in effective
