# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-delegation-chain-whose-warrant-depth-exceeds-its-local-trust-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-federated-delegation-chain-whose-warrant-depth-exceeds-its-local-trust-horizon.warrant.json
# Markdown SHA-256:   b2ffd08e07222176af3e32bb41b2c8fd817a4f66e59a2afe772dab388506975f
# Code AST SHA-256:   8ce1f0733717f685391c52f0d14105694fb346b061037c7c88573c5ed4179700
# Verified Classes:   DelegationHorizonError, Warrant, VerifierPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationHorizonError(RuntimeError):
    """Raised when a federated warrant's depth exceeds the verifier's
    ability to adjudicate revocation and scope-monotonicity for every hop.
    This is a *typed refusal*, not an authentication failure: the token may
    be perfectly valid and still be unadjudicable."""

    def __init__(self, chain_depth: int, horizon: int,
                 unadjudicable_hops: list[int], reason: str):
        self.chain_depth = chain_depth
        self.horizon = horizon
        self.unadjudicable_hops = unadjudicable_hops
        self.reason = reason
        super().__init__(
            f"delegation horizon overflow: depth={chain_depth} "
            f"horizon={horizon} unadjudicable_hops={unadjudicable_hops} "
            f"({reason})"
        )


@dataclass
class Warrant:
    issuer: str
    parent_hash: Optional[str]
    scope: frozenset[str]
    exp: float


@dataclass
class VerifierPolicy:
    # issuers for which we hold a live revocation channel
    revocation_channels: frozenset[str]
    # issuer -> poll interval seconds; must beat freshness_window to count
    poll_intervals: dict[str, float]
    freshness_window: float
    # monotonicity proof coverage: set of chain indices proven by a
    # locally-trusted root. Empty set = no proof.
    proven_hops: frozenset[int]


def _effective_horizon(chain: list[Warrant], policy: VerifierPolicy) -> int:
    """Count upstream issuers we can actually adjudicate. An issuer whose
    poll interval exceeds the freshness window counts as 0 — its revocation
    state is stale between polls."""
    h = 0
    for w in chain[:-1]:  # exclude the immediate parent? no: include all
        if w.issuer in policy.revocation_channels:
            interval = policy.poll_intervals.get(w.issuer, float("inf"))
            if interval <= policy.freshness_window:
                h += 1
    return h


def authorize(warrant: Warrant, chain: list[Warrant],
              policy: VerifierPolicy) -> None:
    """Accept a delegated warrant only if the verifier can prove, for every
    hop beyond its horizon, that scope narrowing was monotone and unrevoked.

    Raises DelegationHorizonError on overflow. Partial proof coverage is
    zero coverage for the uncovered hop — we refuse, never accept 'most'."""
    n = len(chain)
    h = _effective_horizon(chain, policy)

    if n <= h:
        return  # within horizon: every upstream revocation feed is live

    # Depth exceeds horizon: every hop in [0, n-h) must be proof-covered.
    required = set(range(0, n - h))
    covered = required & set(policy.proven_hops)
    uncovered = sorted(required - covered)

    if uncovered:
        raise DelegationHorizonError(
            chain_depth=n,
            horizon=h,
            unadjudicable_hops=uncovered,
            reason="no monotonicity proof covers these hops and no live "
                   "revocation channel reaches their issuers within the "
                   "freshness window",
        )
    # full coverage of the unadjudicable prefix: accept
    return


def handle_federated_call(warrant: Warrant, chain: list[Warrant],
                          policy: VerifierPolicy, action_scope: str) -> str:
    if action_scope not in warrant.scope:
        raise DelegationHorizonError(
            len(chain), _effective_horizon(chain, policy), [],
            f"action {action_scope!r} not in warrant scope",
        )
    authorize(warrant, chain, policy)  # may raise DelegationHorizonError
    return f"executed {action_scope} under warrant from {warrant.issuer}"
