# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-replayed-mcp-tools-call-when-the-transport-resumed-but-the-tool-s-side-effect-already-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-replayed-mcp-tools-call-when-the-transport-resumed-but-the-tool-s-side-effect-already-committed.warrant.json
# Markdown SHA-256:   e99eaed904764fb74d9663f0bb6aa9bbe81f4cd15a3e325c856019f9de61a75a
# Code AST SHA-256:   bfdfdca9a2402bfbd88db08ec2691554d34e453990cbcac80703860256b4dfca
# Verified Classes:   IndeterminateCommitError, EffectClass, CallIdentity, CallState, ResumptionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class IndeterminateCommitError(RuntimeError):
    """Raised when a side-effecting tools/call cannot be proven committed or uncommitted."""
    pass


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    AT_MOST_ONCE = "at_most_once"


@dataclass(frozen=True)
class CallIdentity:
    session_id: str
    idempotency_token: str  # stable across retries; NOT the JSON-RPC id

    @staticmethod
    def derive(session_id: str, tool: str, args: str) -> "CallIdentity":
        token = hashlib.sha256(f"{tool}\x00{args}".encode()).hexdigest()
        return CallIdentity(session_id=session_id, idempotency_token=token)


@dataclass
class CallState:
    identity: CallIdentity
    effect: EffectClass
    committed: bool = False
    response_event_id: int | None = None


class ResumptionLedger:
    """Owns BOTH the event cursor and the invocation cursor; they must not diverge."""

    def __init__(self) -> None:
        self._calls: dict[str, CallState] = {}
        self._last_event_id: int = 0

    def begin(self, identity: CallIdentity, effect: EffectClass) -> CallState:
        state = self._calls.get(identity.idempotency_token)
        if state is None:
            state = CallState(identity=identity, effect=effect)
            self._calls[identity.idempotency_token] = state
        return state

    def on_event(self, event_id: int, token: str) -> None:
        state = self._calls.get(token)
        if state is not None:
            state.committed = True
            state.response_event_id = event_id
        self._last_event_id = max(self._last_event_id, event_id)

    def decide_after_interruption(
        self, identity: CallIdentity, buffer_intact: bool
    ) -> str:
        state = self._calls.get(identity.idempotency_token)
        if state is None:
            raise IndeterminateCommitError(
                f"no invocation record for token {identity.idempotency_token}"
            )
        if state.committed:
            # Response is recoverable via Last-Event-ID replay; never re-issue.
            return "replay_response"
        if state.effect is EffectClass.IDEMPOTENT:
            return "reissue_safe"
        if not buffer_intact:
            # Side-effecting call, commit unknown, buffer gone: fail closed.
            raise IndeterminateCommitError(
                f"side-effecting call {identity.idempotency_token} has "
                f"indeterminate commit state and no replayable buffer"
            )
        # Buffer intact but no terminal event yet: resumption may still deliver it.
        return "resume_stream_only"


def handle_interruption(
    ledger: ResumptionLedger,
    identity: CallIdentity,
    buffer_intact: bool,
) -> str:
    action = ledger.decide_after_interruption(identity, buffer_intact)
    if action == "replay_response":
        # Bind to existing committed result; do not create a new POST.
        return "resume_stream_only"
    if action == "resume_stream_only":
        return "resume_stream_only"
    if action == "reissue_safe":
        return "reissue"
    raise IndeterminateCommitError(f"unhandled action {action}")
