# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-sse-channel-reconnects-between-last-event-id-delivery-and-the-in-flight-req.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-sse-channel-reconnects-between-last-event-id-delivery-and-the-in-flight-req.warrant.json
# Markdown SHA-256:   2ba9c6a134d6cf5ec6399e9d86f0ff11a2483c8d1863fb5fed46a569575c1f8c
# Code AST SHA-256:   04085e33a8a812ca76b5fd5dc84f43c4f61d347b2e27eec3a40ccdd67c9bce91
# Verified Classes:   ResumptionContinuityError, PendingCall, SessionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ResumptionContinuityError(RuntimeError):
    """Raised when SSE resumption cannot prove tool-call continuity."""
    pass


@dataclass
class PendingCall:
    jsonrpc_id: str
    idempotency_key: str
    tool_name: str
    non_idempotent: bool
    cursor_at_send: int
    dispatched: bool = False


@dataclass
class SessionState:
    session_id: str
    last_event_id: int = 0
    pending: dict = field(default_factory=dict)
    # server-advertised: ids the server has committed effects for but not yet
    # emitted response events for. Empty set + no endpoint => unknown.
    server_unanswered: Optional[set] = None
    server_dedup_supported: bool = False


def make_idempotency_key(session_id: str, jsonrpc_id: str, tool_name: str) -> str:
    return hashlib.sha256(
        f"{session_id}:{jsonrpc_id}:{tool_name}".encode()
    ).hexdigest()[:32]


def on_stream_drop(state: SessionState) -> None:
    """Called when the SSE reader raises. Decide replay-wait vs retry."""
    if not state.pending:
        return
    for call in state.pending.values():
        if call.non_idempotent:
            if state.server_unanswered is None:
                raise ResumptionContinuityError(
                    f"non-idempotent call {call.jsonrpc_id} ({call.tool_name}) "
                    f"in flight; server exposes no pending-set endpoint, so "
                    f"outcome is unknown. Refusing to retry — would duplicate "
                    f"a committed side effect. Requires server-side dedup or "
                    f"pending-set advertisement to proceed."
                )
            if call.jsonrpc_id in state.server_unanswered:
                # server proves the request is alive; wait for replay, do not retry
                continue
            # server proves the request is answered but event was lost;
            # only safe to retry if the server dedups on idempotency key
            if not state.server_dedup_supported:
                raise ResumptionContinuityError(
                    f"call {call.jsonrpc_id} answered server-side but response "
                    f"event lost past cursor {state.last_event_id}; server does "
                    f"not honor idempotency keys, retry would re-execute."
                )


def advance_cursor(state: SessionState, event_id: int, routed: bool) -> None:
    """Cursor must advance only after dispatch, not on parse."""
    if not routed:
        raise ResumptionContinuityError(
            f"refusing to advance Last-Event-ID to {event_id}: event parsed "
            f"but not dispatched to pending table; crash here loses the "
            f"response with no replay path (cursor would be past it)."
        )
    state.last_event_id = max(state.last_event_id, event_id)


def resume(state: SessionState, advertised_cursor: int) -> None:
    if advertised_cursor > state.last_event_id:
        raise ResumptionContinuityError(
            f"server cursor {advertised_cursor} ahead of persisted cursor "
            f"{state.last_event_id}; events in between were never dispatched. "
            f"Cold-start gap — reconcile pending table before resuming."
        )
