# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-capability-token-whose-aud-matches-but-whose-delegation-chain-has-an-expired-intermediate-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-capability-token-whose-aud-matches-but-whose-delegation-chain-has-an-expired-intermediate-warrant.warrant.json
# Markdown SHA-256:   b1559130fef5b7f4f052b0ecf2c345f77817c8833b5af069c676a02c9d592805
# Code AST SHA-256:   97b99280b7d7feeceae93195b7ef44ac513300a7c824ff9a787044034b73f987
# Verified Classes:   DelegationChainError, Warrant, ChainVerdict
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when a delegated capability fails chain validation."""
    pass


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    nbf: float
    exp: float
    revoked: bool = False
    link_index: int = -1


@dataclass
class ChainVerdict:
    outcome: str
    offending_link_index: Optional[int] = None
    offending_link_did: Optional[str] = None
    evaluation_instant: float = 0.0
    effective_window: tuple = (0.0, 0.0)
    detail: str = ""


SKEW_TOLERANCE_S = 5.0
IDEMPOTENT_ACTIONS = frozenset({"tool:search:query", "tool:fetch:read"})


def verify_delegation_chain(
    chain: list[Warrant],
    audience: str,
    requested_action: str,
    trust_roots: frozenset,
    now: float,
    action_is_idempotent: bool,
) -> ChainVerdict:
    """
    chain[0] is the root warrant; chain[-1] is the leaf.
    Evaluate every link at a single instant `now`.
    """
    if not chain:
        raise DelegationChainError("empty delegation chain")

    # 1. Structural integrity: issuer/subject linkage and scope monotonicity.
    for i in range(len(chain) - 1):
        parent, child = chain[i], chain[i + 1]
        if parent.subject != child.issuer:
            raise DelegationChainError(
                f"link {i}->{i+1} broken: parent.subject={parent.subject!r} "
                f"!= child.issuer={child.issuer!r}"
            )
        if not parent.scope.issuperset(child.scope):
            raise DelegationChainError(
                f"scope widened at link {i}->{i+1}: "
                f"parent={sorted(parent.scope)} does not dominate child={sorted(child.scope)}"
            )

    # 2. Trust root anchoring.
    if chain[0].issuer not in trust_roots:
        raise DelegationChainError(
            f"root issuer {chain[0].issuer!r} not in trust set"
        )

    # 3. Leaf audience and action coverage.
    leaf = chain[-1]
    if leaf.subject != audience:
        raise DelegationChainError(
            f"leaf audience mismatch: expected {audience!r}, got {leaf.subject!r}"
        )
    if requested_action not in leaf.scope:
        raise DelegationChainError(
            f"action {requested_action!r} outside leaf scope {sorted(leaf.scope)}"
        )

    # 4. Single-instant temporal evaluation across ALL links.
    effective_start = max(w.nbf for w in chain)
    effective_end = min(w.exp for w in chain)

    for i, w in enumerate(chain):
        if w.revoked:
            raise DelegationChainError(
                f"warrant at link {i} ({w.subject!r}) is revoked"
            )
        if now < w.nbf:
            raise DelegationChainError(
                f"warrant at link {i} ({w.subject!r}) not yet valid at t={now}"
            )
        if now >= w.exp:
            # Distinguish leaf expiry from intermediate expiry — critical.
            if i == len(chain) - 1:
                raise DelegationChainError(
                    f"LEAF_EXPIRED: leaf at link {i} expired at {w.exp}, now={now}"
                )
            within_skew = (now - w.exp) <= SKEW_TOLERANCE_S
            if within_skew and action_is_idempotent:
                return ChainVerdict(
                    outcome="AUTHORIZED_DEGRADED",
                    offending_link_index=i,
                    offending_link_did=w.subject,
                    evaluation_instant=now,
                    effective_window=(effective_start, effective_end),
                    detail=(
                        f"intermediate link {i} ({w.subject!r}) expired at {w.exp}, "
                        f"within skew tolerance; degraded authorization for "
                        f"idempotent action {requested_action!r}"
                    ),
                )
            # Hard refusal — do not collapse into LEAF_EXPIRED.
            raise DelegationChainError(
                f"INTERMEDIATE_WARRANT_EXPIRED: link {i} ({w.subject!r}) "
                f"expired at {w.exp}, now={now}, "
                f"skew_exceeded={not within_skew}, "
                f"action_mutable={not action_is_idempotent}; "
                f"recover by re-delegating from link {i-1} issuer, not the lapsed link"
            )

    return ChainVerdict(
        outcome="AUTHORIZED",
        evaluation_instant=now,
        effective_window=(effective_start, effective_end),
        detail=f"chain of {len(chain)} links valid at t={now}",
    )
