# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-streamable-http-mcp-tool-call-across-a-reconnect-and-the-server-has-no-idempotency-key-to-deduplicate-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-streamable-http-mcp-tool-call-across-a-reconnect-and-the-server-has-no-idempotency-key-to-deduplicate-it.warrant.json
# Markdown SHA-256:   887b6b2d321070ca25f32312e766fa85639c215eafed59bf25a4256b5f33639d
# Code AST SHA-256:   d0cb6949b6c07f1aeecf3bf0a9ece24db3db9c494521ac9c6aae1dadf08bead6
# Verified Classes:   ReplaySafetyError, ToolCallState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ReplaySafetyError(RuntimeError):
    """Raised when a side-effecting MCP tool call cannot be safely replayed."""
    pass


@dataclass
class ToolCallState:
    logical_call_id: str
    tool_name: str
    idempotency_key: Optional[str]
    last_event_id: Optional[int]
    side_effecting: bool
    server_dedups_on_key: bool
    result: Optional[str] = None


def make_idempotency_key(logical_call_id: str, tool_name: str, args: str) -> str:
    # Deterministic across checkpoint/resume: never regenerate on retry.
    h = hashlib.sha256(f"{logical_call_id}:{tool_name}:{args}".encode()).hexdigest()
    return f"idem-{h[:32]}"


def plan_reconnect(state: ToolCallState) -> str:
    """Decide whether a reconnect may resend, must reconcile, or must refuse."""
    if not state.side_effecting:
        return "resend_safe"  # read-only: at-least-once is harmless

    if state.result is not None:
        return "already_applied"  # stored result; do not re-execute

    if state.idempotency_key is None:
        # Cursor may exist, but we cannot bind the call to a dedup key.
        raise ReplaySafetyError(
            f"call {state.logical_call_id!r} to {state.tool_name!r} is side-effecting "
            f"but has no persisted idempotency key; outcome unknown, reconcile required"
        )

    if not state.server_dedups_on_key:
        raise ReplaySafetyError(
            f"server does not dedup on idempotency key for {state.tool_name!r}; "
            f"replaying {state.logical_call_id!r} risks duplicate effect"
        )

    if state.last_event_id is None:
        # Key present, cursor lost: safe to resend *with the same key* only.
        return "resend_with_key"

    return "resend_with_key"


def resume_call(state: ToolCallState) -> str:
    action = plan_reconnect(state)
    if action == "already_applied":
        return state.result
    if action == "resend_safe":
        return "resend_read_only"
    if action == "resend_with_key":
        return f"resend:{state.idempotency_key}"
    raise ReplaySafetyError(f"unhandled replay action {action!r}")


# Example: cold-start with cursor but no key on a write tool -> fail closed.
bad = ToolCallState(
    logical_call_id="call-7f3a",
    tool_name="create_ticket",
    idempotency_key=None,
    last_event_id=41,
    side_effecting=True,
    server_dedups_on_key=True,
)
try:
    resume_call(bad)
except ReplaySafetyError as e:
    print(f"refused: {e}")
