# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-identity-key-mid-warrant-and-bridges-a-stale-credential-across-protocol-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-identity-key-mid-warrant-and-bridges-a-stale-credential-across-protocol-boundaries.warrant.json
# Markdown SHA-256:   e4281a9e691ad169cdf8b96d6791922b9eed1190b6337ba18871b7de8942f7cc
# Code AST SHA-256:   751355ca611b4e93043573245450755273163ce4068ae98e7f212838a74b77de
# Verified Classes:   RotationRaceDetected, KeyState, Warrant, KeyRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class RotationRaceDetected(RuntimeError):
    """Raised when a warrant's issuer key is retired but the warrant is still live.

    This is NOT a transient verification error. It must never be retried by the
    presenting agent; it must escalate to the warrant issuer (orchestrator).
    """
    pass


class KeyState(Enum):
    CURRENT = "current"
    RETIRED = "retired"      # still verifiable, within grace window
    PURGED = "purged"        # no longer verifiable, must fail closed


@dataclass(frozen=True)
class Warrant:
    subject: str
    capability: str
    scope: str
    expiry: int
    issuer_key_id: str
    signature: bytes


@dataclass(frozen=True)
class KeyRecord:
    key_id: str
    state: KeyState
    retired_at: Optional[int]


def bridge_warrant(
    warrant: Warrant,
    registry: dict[str, KeyRecord],
    now: int,
    presenter_current_key_id: str,
) -> dict:
    """Translate a warrant across a protocol boundary.

    INVARIANT: the outbound sender_identity MUST be the warrant's issuer_key_id,
    never the presenter's current key. If the issuer key is retired while the
    warrant is live, fail with RotationRaceDetected (terminal, escalate).
    """
    issuer = registry.get(warrant.issuer_key_id)
    if issuer is None:
        raise RotationRaceDetected(
            f"issuer key {warrant.issuer_key_id} absent from registry; "
            f"cannot anchor warrant for {warrant.subject}; fail closed"
        )

    if issuer.state is KeyState.PURGED:
        raise RotationRaceDetected(
            f"issuer key {warrant.issuer_key_id} purged before warrant expiry "
            f"(expiry={warrant.expiry}, now={now}); warrant unverifiable"
        )

    if issuer.state is KeyState.RETIRED and now < warrant.expiry:
        # The exact race: retired key, live warrant, presenter already rotated.
        raise RotationRaceDetected(
            f"rotation race: warrant signed by retired key "
            f"{warrant.issuer_key_id} (retired_at={issuer.retired_at}) "
            f"is live until {warrant.expiry}; presenter now holds "
            f"{presenter_current_key_id}. Escalate to issuer for re-issue; "
            f"do NOT re-anchor to current key and do NOT retry."
        )

    if presenter_current_key_id != warrant.issuer_key_id:
        # Presenter has rotated but warrant is still valid under old key and
        # within grace: forward with provenance preserved, flag the divergence.
        return {
            "sender_identity": warrant.issuer_key_id,  # NOT presenter_current
            "warrant": warrant,
            "bridge_epoch": now,
            "identity_divergence": presenter_current_key_id,
        }

    return {
        "sender_identity": warrant.issuer_key_id,
        "warrant": warrant,
        "bridge_epoch": now,
        "identity_divergence": None,
    }
