# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-cross-issuer-trust-anchor-in-delegated-aaif-agent-credential-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-cross-issuer-trust-anchor-in-delegated-aaif-agent-credential-chains.warrant.json
# Markdown SHA-256:   b3c2a1d47d4276eae87927b679e88138fd93039b9f5cc221fffa95c328b78ff1
# Code AST SHA-256:   49dd17092106349e5542ec25f1a815514aaa8e523eac2f74d70cc1e56a5095d4
# Verified Classes:   AnchorResolutionError, TerminationReason, ChainLink, VerificationResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class AnchorResolutionError(RuntimeError):
    """Raised when a delegated credential chain cannot be closed at a configured trust anchor."""


class TerminationReason(Enum):
    ANCHOR_HIT = "anchor_hit"
    TRANSPORT_ERROR = "transport_error"
    JWKS_UNREACHABLE = "jwks_unreachable"
    CACHE_MISS_FALLBACK = "cache_miss_fallback"


@dataclass(frozen=True)
class ChainLink:
    issuer: str
    parent_issuer: Optional[str]
    delegated_scope: frozenset


@dataclass(frozen=True)
class VerificationResult:
    valid: bool
    terminating_issuer: str
    termination_reason: TerminationReason
    anchor_set_id: str
    effective_scope: frozenset


def verify_delegated_chain(
    chain: list[ChainLink],
    configured_anchors: frozenset,
    anchor_set_id: str,
    jwks_reachable: dict,
) -> VerificationResult:
    """
    Walk a delegated chain leaf->root. The chain is valid ONLY if it terminates
    at a configured anchor via an explicit anchor hit. Any fallback to a nearer
    link is a hard failure -- never a degraded success.
    """
    effective_scope = chain[0].delegated_scope
    for link in chain:
        effective_scope = effective_scope & link.delegated_scope  # intersection, not leaf scope

    current = chain[-1]
    if current.parent_issuer is None:
        # terminal link claims to be a root
        if current.issuer not in configured_anchors:
            raise AnchorResolutionError(
                f"chain claims root {current.issuer!r} not in anchor set {anchor_set_id}"
            )
        reason = TerminationReason.ANCHOR_HIT
        terminator = current.issuer
    else:
        parent = current.parent_issuer
        if not jwks_reachable.get(parent, False):
            # CRITICAL: do NOT promote `current.issuer` to anchor. Raise.
            raise AnchorResolutionError(
                f"anchor {parent!r} unreachable during chain walk; "
                f"refusing to substitute {current.issuer!r} as de-facto anchor"
            )
        if parent not in configured_anchors:
            raise AnchorResolutionError(
                f"parent issuer {parent!r} not in anchor set {anchor_set_id}"
            )
        reason = TerminationReason.ANCHOR_HIT
        terminator = parent

    return VerificationResult(
        valid=True,
        terminating_issuer=terminator,
        termination_reason=reason,
        anchor_set_id=anchor_set_id,
        effective_scope=effective_scope,
    )


def gate_on_result(result: VerificationResult, expected_anchor_set_id: str) -> None:
    """Every consumer must gate on provenance, not on the boolean."""
    if result.termination_reason is not TerminationReason.ANCHOR_HIT:
        raise AnchorResolutionError(
            f"silent anchor substitution detected: reason={result.termination_reason}"
        )
    if result.anchor_set_id != expected_anchor_set_id:
        raise AnchorResolutionError(
            f"anchor-set divergence: verifier used {result.anchor_set_id!r}, "
            f"consumer expects {expected_anchor_set_id!r}"
        )
