# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-anchor-a-federated-peer-s-transitive-trust-chain-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-anchor-a-federated-peer-s-transitive-trust-chain-mid-handoff.warrant.json
# Markdown SHA-256:   14814b336da56db704ec4744891579f549411690f0403599da5f65d9c03bac96
# Code AST SHA-256:   fff8cad9aa0fff670108a0edf3f778fa7404c7158d01b7190001645ef372f8b1
# Verified Classes:   TrustPathDivergence, Policy, TrustPath
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple


class TrustPathDivergence(RuntimeError):
    """Raised when two valid trust paths to a local anchor carry non-equivalent policies."""


@dataclass(frozen=True)
class Policy:
    max_tokens_per_call: int
    data_classes: FrozenSet[str]

    def fingerprint(self) -> Tuple[int, Tuple[str, ...]]:
        return (self.max_tokens_per_call, tuple(sorted(self.data_classes)))


@dataclass(frozen=True)
class TrustPath:
    path_id: str
    policy: Policy
    anchor_valid_until: int  # epoch seconds
    revoked: bool = False


def canonical_path(paths: Tuple[TrustPath, ...], now: int) -> TrustPath:
    valid = [p for p in paths if not p.revoked and p.anchor_valid_until > now]
    if not valid:
        raise TrustPathDivergence("no valid, non-revoked trust path to local anchor")

    fingerprints = {p.policy.fingerprint() for p in valid}
    if len(fingerprints) > 1:
        raise TrustPathDivergence(
            f"valid paths diverge on policy: {sorted(fingerprints)}; "
            "refusing to merge — re-issue warrant under current trust config"
        )

    # Policy-equivalent paths: select narrowest, then most-recent anchor, then stable id.
    return min(valid, key=lambda p: (p.policy.max_tokens_per_call,
                                     -p.anchor_valid_until, p.path_id))


def authorize(warrant_paths: Tuple[TrustPath, ...], action_data_class: str,
              requested_tokens: int, now: int) -> bool:
    path = canonical_path(warrant_paths, now)
    if action_data_class not in path.policy.data_classes:
        return False
    if requested_tokens > path.policy.max_tokens_per_call:
        return False
    return True
