# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-capability-token-whose-consent-chain-is-structurally-valid-but-temporally-incoherent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-capability-token-whose-consent-chain-is-structurally-valid-but-temporally-incoherent.warrant.json
# Markdown SHA-256:   e5f61e31b38a14df5cbc5d622a57f2fd134fb3e32631d8225d77eb10f9e3f082
# Code AST SHA-256:   85f0a0dc2ece13a1540be98dab220697a2a9c401cc64d9fccbaa0caf64ecd706
# Verified Classes:   GrantState, StateInterval, ChainLink, TemporalIncoherenceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
from typing import Sequence


class GrantState(Enum):
    ACTIVE = "active"
    SUSPENDED = "suspended"
    REVOKED = "revoked"


@dataclass(frozen=True)
class StateInterval:
    state: GrantState
    start: datetime
    end: datetime | None  # None means open-ended


@dataclass(frozen=True)
class ChainLink:
    principal: str
    grant_id: str
    scope: frozenset[str]
    minted_at: datetime
    state_history: Sequence[StateInterval]


class TemporalIncoherenceError(RuntimeError):
    """Raised when a structurally valid consent chain is temporally incoherent:
    a child link was minted while its parent grant was not ACTIVE.
    This taint is non-monotonic and cannot be cleared by later unsuspension."""


def _state_at(history: Sequence[StateInterval], t: datetime) -> GrantState | None:
    for iv in history:
        if iv.start <= t and (iv.end is None or t < iv.end):
            return iv.state
    return None


def verify_chain(chain: Sequence[ChainLink], *, max_skew: timedelta) -> None:
    if len(chain) < 2:
        return  # single-hop: no delegation to check

    for parent, child in zip(chain, chain[1:]):
        if child.scope - parent.scope:
            raise TemporalIncoherenceError(
                f"scope escalation: {child.principal} exceeds {parent.principal}"
            )

        # Reconstruct the parent's state at the child's mint event.
        state = _state_at(parent.state_history, child.minted_at)

        if state is None:
            # No state record covers the mint instant. Ambiguous; fail closed.
            raise TemporalIncoherenceError(
                f"no state history for {parent.grant_id} at mint of "
                f"{child.grant_id} ({child.minted_at.isoformat()})"
            )

        if state is not GrantState.ACTIVE:
            # The core boundary: minted during a non-ACTIVE window.
            # Unsuspension later does not clear this.
            raise TemporalIncoherenceError(
                f"{child.grant_id} minted by {parent.principal} at "
                f"{child.minted_at.isoformat()} while parent grant "
                f"{parent.grant_id} was {state.value}; chain is tainted"
            )

        # Clock-skew guard: if the mint event precedes the parent's own
        # activation by more than max_skew, the timestamps are unreliable.
        activation = min(
            (iv.start for iv in parent.state_history if iv.state is GrantState.ACTIVE),
            default=None,
        )
        if activation is not None and child.minted_at + max_skew < activation:
            raise TemporalIncoherenceError(
                f"mint of {child.grant_id} precedes parent activation by more "
                f"than {max_skew}; timestamps unreliable, rejecting"
            )
