# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-aaif-delegation-chains-when-credential-attenuation-is-non-monotonic-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-aaif-delegation-chains-when-credential-attenuation-is-non-monotonic-across-agent-hops.warrant.json
# Markdown SHA-256:   f4ccbac2e16b04dc48f306b9117186a34b31677e82b1a87cfc4a30c2005642f1
# Code AST SHA-256:   27b8251f0cd742588baf0fc57be236bfcc3a8941db1ab5978dee76fce5f30334
# Verified Classes:   DelegationChainRejected, Hop
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class DelegationChainRejected(RuntimeError):
    """Raised when an AAIF delegation chain cannot be validated as monotonic
    under a common vocabulary refinement. The chain must not be honored."""


@dataclass(frozen=True)
class Hop:
    scope: frozenset[str]
    vocab_revision: str
    vocab_digest: str


def validate_chain(
    hops: list[Hop],
    local_digest: str,
    refinements: Mapping[tuple[str, str], str],
) -> str:
    """Return the refinement witness digest if the chain is valid, else raise.

    `refinements` maps an unordered pair of vocab digests to the digest of a
    published common refinement. A missing pair means the two vocabularies are
    semantically incomparable and the chain cannot be validated.
    """
    if not hops:
        raise DelegationChainRejected("empty delegation chain")

    digests = {h.vocab_digest for h in hops}
    if len(digests) == 1:
        digest = next(iter(digests))
        if digest != local_digest:
            raise DelegationChainRejected(
                f"single-vocabulary chain signed under {digest!r} "
                f"but verifier is pinned to {local_digest!r}; "
                f"cannot attest scope under a foreign vocabulary"
            )
        for parent, child in zip(hops, hops[1:]):
            if not child.scope <= parent.scope:
                raise DelegationChainRejected(
                    f"non-monotonic attenuation: {child.scope!r} not subset of "
                    f"{parent.scope!r} under {digest!r}"
                )
        return digest

    # Mixed-vocabulary chain: require a refinement for every adjacent pair.
    witness = None
    for parent, child in zip(hops, hops[1:]):
        if parent.vocab_digest == child.vocab_digest:
            continue
        key = tuple(sorted((parent.vocab_digest, child.vocab_digest)))
        refinement = refinements.get(key)
        if refinement is None:
            raise DelegationChainRejected(
                f"no published refinement between {parent.vocab_digest!r} and "
                f"{child.vocab_digest!r}; attenuation is non-monotonic across "
                f"this hop and cannot be validated"
            )
        if witness is not None and refinement != witness:
            raise DelegationChainRejected(
                f"inconsistent refinements across chain: {witness!r} vs "
                f"{refinement!r}; composed attenuation is undefined"
            )
        witness = refinement

    if witness is None:
        raise DelegationChainRejected("mixed-vocabulary chain without refinement")

    # Re-check subset under the common refinement, not under local vocabulary.
    for parent, child in zip(hops, hops[1:]):
        if not _subset_under_refinement(child.scope, parent.scope, witness):
            raise DelegationChainRejected(
                f"child scope {child.scope!r} not subset of parent "
                f"{parent.scope!r} under refinement {witness!r}"
            )
    return witness


def _subset_under_refinement(
    child: frozenset[str], parent: frozenset[str], refinement: str
) -> bool:
    # Resolution is delegated to the refinement engine keyed by `refinement`.
    # A missing engine is a hard failure, never a silent local fallback.
    engine = _REFINEMENT_ENGINES.get(refinement)
    if engine is None:
        raise DelegationChainRejected(
            f"refinement {refinement!r} is not resolvable by this instance; "
            f"refusing to substitute the local vocabulary"
        )
    return engine.subset(child, parent)


_REFINEMENT_ENGINES: dict = {}
