# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-warrant-identity-split-during-cross-org-mutual-attestation-when-the-peer-s-signing-key-rotates-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-warrant-identity-split-during-cross-org-mutual-attestation-when-the-peer-s-signing-key-rotates-mid-handshake.warrant.json
# Markdown SHA-256:   c462e9bac52a7d43dadd4dea9de223da6eac37725cb030dc44c626c6973d71df
# Code AST SHA-256:   4e62f2c35407b094a0fbed07cdd3c80bd79f8c7354a0c9e0322b5828a017c816
# Verified Classes:   WarrantEpochSplitError, HandshakeContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantEpochSplitError(RuntimeError):
    """Raised when attestation epoch, warrant epoch, and revocation epoch diverge
    such that a valid-looking signature would authorize against stale revocation state."""


@dataclass(frozen=True)
class HandshakeContext:
    subject: str
    attestation_key_epoch: int
    warrant_epoch: int
    revocation_epoch: int
    older_epoch_revocation_current: bool


def authorize_cross_org(
    ctx: HandshakeContext,
    resource: str,
    revocation_index: dict[tuple[int, str, str], bool],
) -> bool:
    epochs = {ctx.attestation_key_epoch, ctx.warrant_epoch, ctx.revocation_epoch}

    if len(epochs) > 1:
        # Epochs disagree: only safe if the older epoch's revocation state is current
        # and we join revocations across every epoch up to the newest in the window.
        if not ctx.older_epoch_revocation_current:
            raise WarrantEpochSplitError(
                f"epoch split for subject={ctx.subject} resource={resource}: "
                f"attest={ctx.attestation_key_epoch} "
                f"warrant={ctx.warrant_epoch} "
                f"revocation={ctx.revocation_epoch}; "
                f"older-epoch revocation not current -> fail closed"
            )
        max_epoch = max(epochs)
        for epoch in range(min(epochs), max_epoch + 1):
            if revocation_index.get((epoch, ctx.subject, resource)):
                return False
        return True

    # Epochs agree: single-epoch check.
    epoch = ctx.warrant_epoch
    if revocation_index.get((epoch, ctx.subject, resource)):
        return False
    return True


def exercise_capability(ctx: HandshakeContext, resource: str, revocation_index: dict) -> str:
    if not authorize_cross_org(ctx, resource, revocation_index):
        raise WarrantEpochSplitError(
            f"capability denied for {ctx.subject} on {resource}: revoked in window"
        )
    return f"granted:{resource}"
