# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-attestation-that-is-valid-but-non-transitive.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-attestation-that-is-valid-but-non-transitive.warrant.json
# Markdown SHA-256:   1d74ee41a8ac975922c7f6b328cd801a9e80c44d7f272ef7d6adeca10f4b22df
# Code AST SHA-256:   16571ea166526d586d84fad705963ea24cd42fd9fc2572b0e3e684ee3162117d
# Verified Classes:   NonTransitiveAttestationError, DelegationEdge, ConsumerPolicy
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class NonTransitiveAttestationError(RuntimeError):
    """Raised when a brokered capability attestation cannot be safely consumed
    because delegation authority is not transitive across the chain."""


@dataclass(frozen=True)
class DelegationEdge:
    issuer: str
    subject: str
    capability: str
    holder_scope: Optional[int]      # what the issuer actually holds
    delegator_scope: Optional[int]   # what the issuer is permitted to delegate
    delegated_scope: Optional[int]   # what the issuer is granting downstream
    declared_depth: int
    broker_policy_version: str


@dataclass(frozen=True)
class ConsumerPolicy:
    pinned_broker_version: str
    max_acceptable_depth: int
    audited_brokers: frozenset


def validate_chain(
    chain: list[DelegationEdge],
    policy: ConsumerPolicy,
    consumer_domain: str,
) -> None:
    if not chain:
        raise NonTransitiveAttestationError("empty attestation chain")

    # Reconstruct true depth from edges; compare to declared depth.
    true_depth = len(chain)
    declared = chain[-1].declared_depth
    if declared != true_depth:
        raise NonTransitiveAttestationError(
            f"depth flattening: declared={declared} true={true_depth}; "
            "provenance edge collapsed, consumer cannot evaluate omitted hop"
        )

    if true_depth > policy.max_acceptable_depth:
        raise NonTransitiveAttestationError(
            f"chain depth {true_depth} exceeds policy max {policy.max_acceptable_depth}"
        )

    for edge in chain:
        # Holding is necessary but not sufficient; delegation authority is separate.
        if edge.delegator_scope is None:
            raise NonTransitiveAttestationError(
                f"issuer {edge.issuer} signed delegation for {edge.capability} "
                "without a delegation-authority scope; possession mistaken for authority"
            )
        if edge.holder_scope is None or edge.delegator_scope > edge.holder_scope:
            raise NonTransitiveAttestationError(
                f"issuer {edge.issuer} delegates scope {edge.delegator_scope} "
                f"but holds {edge.holder_scope}"
            )
        if edge.delegated_scope is None or edge.delegated_scope > edge.delegator_scope:
            raise NonTransitiveAttestationError(
                f"issuer {edge.issuer} grants {edge.delegated_scope} "
                f"exceeding delegation authority {edge.delegator_scope}"
            )
        # Broker policy version must match what the consumer pinned.
        if edge.issuer not in policy.audited_brokers:
            raise NonTransitiveAttestationError(
                f"broker {edge.issuer} not in consumer's audited set"
            )
        if edge.broker_policy_version != policy.pinned_broker_version:
            raise NonTransitiveAttestationError(
                f"broker policy drift: edge={edge.broker_policy_version} "
                f"pinned={policy.pinned_broker_version}; re-federation required"
            )

    # Terminal subject must be the consumer; otherwise we are evaluating
    # a chain not addressed to us (replay / misrouting).
    if chain[-1].subject != consumer_domain:
        raise NonTransitiveAttestationError(
            f"chain terminates at {chain[-1].subject}, not consumer {consumer_domain}"
        )
