# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-credential-chain-when-a-revocation-epoch-has-advanced-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-credential-chain-when-a-revocation-epoch-has-advanced-mid-handoff.warrant.json
# Markdown SHA-256:   a9e8bf1d64d0cc6ebe0e48e00d80ac4af2f5cbac6818298b6579c4b2ea4daa98
# Code AST SHA-256:   7abf9fb11636ca0868e253b3da73a7c1b65a858700a1cabee5a4ebdeb7e17b98
# Verified Classes:   DelegationAuthorityError, ChainVerdict, DelegationLink, CachedChain, EpochRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class DelegationAuthorityError(RuntimeError):
    """Raised when a delegated chain cannot be honored at commit time."""


class ChainVerdict(Enum):
    HONOR = "honor"
    REDELEGATE = "redelegate"
    ABORT = "abort"


@dataclass(frozen=True)
class DelegationLink:
    issuer: str
    delegate: str
    chain_epoch_at_issue: int
    not_before: int
    not_after: int
    delegate_can_redelegate: bool


@dataclass
class CachedChain:
    links: list[DelegationLink]
    cached_epoch: int


@dataclass
class EpochRegistry:
    """Authoritative per-issuer epoch and per-link revocation scope."""
    epoch: dict[str, int] = field(default_factory=dict)
    revoked_links: set[tuple[str, str]] = field(default_factory=set)

    def current_epoch(self, issuer: str) -> int:
        if issuer not in self.epoch:
            raise DelegationAuthorityError(
                f"issuer {issuer!r} has no published epoch; cannot validate"
            )
        return self.epoch[issuer]

    def link_revoked(self, issuer: str, delegate: str) -> bool:
        return (issuer, delegate) in self.revoked_links


def evaluate_chain_at_commit(
    chain: CachedChain,
    registry: EpochRegistry,
    now: int,
    acting_link_index: int,
) -> ChainVerdict:
    """
    Commit-time gate. Must be called immediately before any state-changing
    action under delegated authority, not at ingress.
    """
    if not chain.links:
        raise DelegationAuthorityError("empty delegation chain")

    # Epoch regression across any link is hostile (split-brain or rollback).
    for link in chain.links:
        auth_epoch = registry.current_epoch(link.issuer)
        if auth_epoch < link.chain_epoch_at_issue:
            raise DelegationAuthorityError(
                f"epoch regression for issuer {link.issuer!r}: "
                f"auth={auth_epoch} < issued={link.chain_epoch_at_issue}"
            )
        if not (link.not_before <= now <= link.not_after):
            raise DelegationAuthorityError(
                f"link {link.issuer}->{link.delegate} outside validity window"
            )

    # Re-walk from root; find the highest still-valid prefix.
    highest_valid = -1
    for i, link in enumerate(chain.links):
        if registry.link_revoked(link.issuer, link.delegate):
            break
        highest_valid = i

    if highest_valid < 0:
        # Root itself revoked: no authority survives.
        return ChainVerdict.ABORT

    if highest_valid < acting_link_index:
        # The link we are acting under is revoked, but an ancestor survives.
        # Re-derive from the highest valid prefix; do not silently downgrade.
        return ChainVerdict.REDELEGATE

    # All links up to and including the acting link remain authorized.
    # Refresh the cache epoch to the current authoritative value.
    chain.cached_epoch = registry.current_epoch(chain.links[acting_link_index].issuer)
    return ChainVerdict.HONOR


def commit_delegated_action(
    chain: CachedChain,
    registry: EpochRegistry,
    now: int,
    acting_link_index: int,
    action: str,
) -> None:
    verdict = evaluate_chain_at_commit(chain, registry, now, acting_link_index)
    if verdict is ChainVerdict.ABORT:
        raise DelegationAuthorityError(
            f"root authority revoked; refusing action {action!r}"
        )
    if verdict is ChainVerdict.REDELEGATE:
        raise DelegationAuthorityError(
            f"acting link revoked mid-task; must re-delegate before {action!r}"
        )
    # HONOR: proceed.
    return None
