# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-aaif-credential-chain-truncation-during-delegated-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-aaif-credential-chain-truncation-during-delegated-verification.warrant.json
# Markdown SHA-256:   8bc9127f041e79d2b2c487aefaf05a14e57610a8e349518255b75c0edacb9910
# Code AST SHA-256:   950674a7277167058a1e8e163ced31549623555c6b4f2bd7c666f69fc29c18b4
# Verified Classes:   AAIFChainTruncationError, Link
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AAIFChainTruncationError(RuntimeError):
    """Raised when a presented AAIF chain is structurally shorter than the
    ancestry the trust anchor committed to via delegation_depth_used."""


@dataclass
class Link:
    issuer: str
    subject: str
    scope: frozenset
    depth_used: int          # signed counter, present on anchor link
    issuer_key_source: str   # "embedded-parent" or "registry"


def verify_chain(presented: list[Link], anchor_subject: str) -> None:
    if not presented:
        raise AAIFChainTruncationError("empty chain presented")

    anchor = presented[0]
    if anchor.issuer != anchor_subject:
        raise AAIFChainTruncationError(
            f"first link issuer {anchor.issuer!r} is not the pinned anchor"
        )

    # Signal 1: signed depth counter must equal number of hops presented.
    hops_presented = len(presented) - 1
    if anchor.depth_used != hops_presented:
        raise AAIFChainTruncationError(
            f"anchor committed to depth {anchor.depth_used} but chain "
            f"presents {hops_presented} hop(s); {anchor.depth_used - hops_presented} "
            f"link(s) dropped"
        )

    # Signal 3: non-anchor links must resolve keys from the presented parent,
    # never from a global registry fallback.
    for i, link in enumerate(presented[1:], start=1):
        if link.issuer_key_source != "embedded-parent":
            raise AAIFChainTruncationError(
                f"link {i} resolved issuer key from {link.issuer_key_source!r}; "
                f"registry fallback masks a missing parent link"
            )
        if link.issuer != presented[i - 1].subject:
            raise AAIFChainTruncationError(
                f"link {i} issuer {link.issuer!r} does not match parent "
                f"subject {presented[i - 1].subject!r}"
            )

    # Signal 2: scope must narrow monotonically along the verified chain.
    for i in range(1, len(presented)):
        if not presented[i].scope.issubset(presented[i - 1].scope):
            raise AAIFChainTruncationError(
                f"link {i} scope {set(presented[i].scope)} is not a subset of "
                f"parent scope {set(presented[i - 1].scope)}"
            )
