# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-did-authenticated-capability-token-that-verifies-cryptographically-but-whose-delegation-chain-exceeds-its-trust-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-did-authenticated-capability-token-that-verifies-cryptographically-but-whose-delegation-chain-exceeds-its-trust-horizon.warrant.json
# Markdown SHA-256:   6ab02489af62d166b5c9ef0ad316b88ea51ab7d43d6ecbc2ed5e71d7196848ba
# Code AST SHA-256:   3c386611e8bc921705afe6737eb5425d42a52c00a75c23c4894e7d4f03205944
# Verified Classes:   UntrustedDelegationRoot, DelegationDepthExceeded, NonMonotoneDelegation, DelegationLink, TrustAnchor
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UntrustedDelegationRoot(RuntimeError):
    """Raised when a capability chain's root is not anchored in local trust policy."""


class DelegationDepthExceeded(RuntimeError):
    """Raised when chain length exceeds the anchor's declared max_delegation_depth."""


class NonMonotoneDelegation(RuntimeError):
    """Raised when a delegation link widens scope or extends expiry beyond its parent."""


@dataclass(frozen=True)
class DelegationLink:
    issuer_did: str
    subject_did: str
    scope: frozenset
    expires_at: int
    signature_valid: bool


@dataclass(frozen=True)
class TrustAnchor:
    did: str
    may_delegate: bool
    max_delegation_depth: int
    revocation_endpoint: Optional[str]


def verify_capability_chain(
    chain: list[DelegationLink],
    anchors: dict[str, TrustAnchor],
    requested_scope: frozenset,
    now: int,
) -> None:
    if not chain:
        raise UntrustedDelegationRoot("empty chain: no root to anchor")

    for link in chain:
        if not link.signature_valid:
            raise UntrustedDelegationRoot(
                f"link {link.issuer_did}->{link.subject_did} failed signature check"
            )

    root_did = chain[-1].issuer_did
    anchor = anchors.get(root_did)
    if anchor is None:
        raise UntrustedDelegationRoot(
            f"chain root {root_did} is not in local trust anchor set; "
            f"cryptographic validity does not imply authorization"
        )
    if len(chain) > 1 and not anchor.may_delegate:
        raise UntrustedDelegationRoot(
            f"anchor {root_did} is not permitted to serve as transitive root"
        )
    if len(chain) > anchor.max_delegation_depth:
        raise DelegationDepthExceeded(
            f"chain length {len(chain)} exceeds anchor bound "
            f"{anchor.max_delegation_depth} for {root_did}"
        )

    # Walk root -> leaf asserting monotone narrowing.
    ordered = list(reversed(chain))
    parent_scope = ordered[0].scope
    parent_expiry = ordered[0].expires_at
    for link in ordered[1:]:
        if not link.scope.issubset(parent_scope):
            raise NonMonotoneDelegation(
                f"link to {link.subject_did} widens scope beyond parent"
            )
        if link.expires_at > parent_expiry:
            raise NonMonotoneDelegation(
                f"link to {link.subject_did} extends expiry beyond parent"
            )
        parent_scope, parent_expiry = link.scope, link.expires_at

    leaf = chain[0]
    if not requested_scope.issubset(leaf.scope):
        raise UntrustedDelegationRoot(
            f"requested scope {requested_scope} not covered by leaf grant {leaf.scope}"
        )
    if leaf.expires_at <= now:
        raise UntrustedDelegationRoot("leaf capability expired")
