# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-warrant-chain-exceeds-its-own-trust-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-warrant-chain-exceeds-its-own-trust-horizon.warrant.json
# Markdown SHA-256:   78f0cbe37f351ff9240ee0ec1ac0f267945380f939ae0aefbff3a55533b48842
# Code AST SHA-256:   8463d08df753d917a2d3bffe30026c09b26f082f2e200baffa6da2cd3f8445ff
# Verified Classes:   UnreachableWarrantError, Hop, TrustState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnreachableWarrantError(RuntimeError):
    """Raised when a brokered capability's warrant chain is valid but its
    effective origin lies outside the consumer's trust horizon, or when a
    live capability's reachability path has been severed by revocation."""


@dataclass(frozen=True)
class Hop:
    delegator: str
    delegatee: str
    origin: str          # the principal whose authority this hop carries
    is_relay: bool       # True if delegator is passing through an upstream grant


@dataclass(frozen=True)
class TrustState:
    anchors: frozenset[str]
    relay_authorizations: frozenset[tuple[str, str]]  # (anchor, relay) pairs


def effective_origin(chain: list[Hop]) -> str:
    """Collapse relay hops: the origin is the upstream principal, not the relay."""
    if not chain:
        raise UnreachableWarrantError("empty warrant chain")
    return chain[0].origin


def is_reachable(chain: list[Hop], trust: TrustState) -> bool:
    """A chain is reachable iff its final hop's delegator is an anchor acting
    as principal (not a relay), or is an explicitly authorized relay whose
    upstream origin is itself the anchored principal."""
    if not chain:
        return False
    final = chain[-1]
    if final.delegator not in trust.anchors:
        return False
    if not final.is_relay:
        # Anchor signed in its own capacity: origin must be the anchor itself.
        return effective_origin(chain) == final.delegator
    # Anchor is relaying: only admissible if it explicitly authorized relaying
    # for this upstream origin.
    return (final.delegator, effective_origin(chain)) in trust.relay_authorizations


def admit_capability(chain: list[Hop], trust: TrustState) -> str:
    if not is_reachable(chain, trust):
        origin = effective_origin(chain) if chain else "<none>"
        raise UnreachableWarrantError(
            f"warrant origin {origin!r} is outside trust horizon; "
            f"anchored link is a relay without explicit authorization"
        )
    return effective_origin(chain)


def revalidate_live(capability_origin: str, chain: list[Hop], trust: TrustState) -> None:
    """Called on checkpoint/resume and on every trust-set mutation."""
    if not is_reachable(chain, trust):
        raise UnreachableWarrantError(
            f"live capability origin {capability_origin!r} no longer reachable "
            f"after trust-set change; capability must be re-derived, not resumed"
        )
