# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-agent-capability-whose-attenuation-chain-is-valid-but-whose-revocation-horizon-is-shorter-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-agent-capability-whose-attenuation-chain-is-valid-but-whose-revocation-horizon-is-shorter-th.warrant.json
# Markdown SHA-256:   a6ee1832bf1a108b490a71caa9262bf04a15a074dd48136babd010d25d4459e3
# Code AST SHA-256:   a3d64c1c8034e166ea8ea982b1b2175e1fc462b82baaf9b538eaaa75bc86c853
# Verified Classes:   RevocationHorizonInsufficient, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class RevocationHorizonInsufficient(RuntimeError):
    """Raised when a delegation chain's minimum horizon cannot cover the task."""


@dataclass(frozen=True)
class Hop:
    delegator: str
    scope: frozenset[str]
    issued_at: float
    horizon: float  # absolute time after which this hop is revoked


def admit_delegation(
    chain: Sequence[Hop],
    now: float,
    expected_duration: float,
    clock_skew_epsilon: float = 0.5,
) -> Hop:
    if not chain:
        raise RevocationHorizonInsufficient("empty delegation chain")

    # Invariant 1: attenuation monotonicity (each scope is a subset of its parent).
    for parent, child in zip(chain, chain[1:]):
        if not child.scope.issubset(parent.scope):
            raise RevocationHorizonInsufficient(
                f"attenuation violated: {child.delegator} scope not subset of {parent.delegator}"
            )

    # Invariant 2: liveness at admission.
    for hop in chain:
        if hop.horizon <= now:
            raise RevocationHorizonInsufficient(
                f"{hop.delegator} revoked at {hop.horizon}, now={now}"
            )

    # Invariant 3: liveness through completion — the non-obvious one.
    min_horizon = min(hop.horizon for hop in chain)
    required = now + expected_duration + clock_skew_epsilon
    if min_horizon <= required:
        deficit = required - min_horizon
        binding = min(chain, key=lambda h: h.horizon)
        raise RevocationHorizonInsufficient(
            f"binding hop {binding.delegator} horizon {min_horizon} "
            f"cannot cover task of {expected_duration}s; deficit {deficit:.2f}s"
        )

    return min(chain, key=lambda h: h.horizon)
