# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-http-native-sse-stream-resumption-as-unsafe-without-a-monotonic-event-cursor-and-how-does-reconnection-si.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-http-native-sse-stream-resumption-as-unsafe-without-a-monotonic-event-cursor-and-how-does-reconnection-si.warrant.json
# Markdown SHA-256:   b456e38b64e3111e945d99a8ce71ebcb76f5dd8477f592082fab5770d54d523f
# Code AST SHA-256:   944fcedab1e84309f60777fd2dba005fc60d0dd1a3681094c8a9ff0dcbfc3dca
# Verified Classes:   ResumptionIntegrityError, CallState, ToolCall, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ResumptionIntegrityError(RuntimeError):
    """Raised when an SSE reconnect cannot prove logical stream continuity."""


class CallState(Enum):
    PENDING = "pending"
    UNKNOWN = "unknown"      # issued, but completion is no longer observable
    DONE = "done"


@dataclass
class ToolCall:
    request_id: str
    idempotency_key: str
    state: CallState = CallState.PENDING


@dataclass
class Session:
    session_id: str
    durable_cursors: bool          # server-advertised capability at init
    last_acked_event_id: int = 0
    calls: dict[str, ToolCall] = field(default_factory=dict)


def _idem_key(request_id: str, payload: bytes) -> str:
    return hashlib.sha256(request_id.encode() + payload).hexdigest()


def on_reconnect(session: Session, first_received_id: int) -> None:
    """
    Called immediately after the SSE channel re-establishes, before any
    event is dispatched to the reasoning loop.
    """
    expected = session.last_acked_event_id + 1

    if session.durable_cursors:
        # Continuation is only legal if the server replays the exact gap.
        if first_received_id != expected:
            # Gap, rollback, or rollover -> server contract violated.
            _demote_gap_spanning_calls(session)
            raise ResumptionIntegrityError(
                f"session {session.session_id}: cursor discontinuity on "
                f"durable stream (expected {expected}, got {first_received_id}); "
                f"demoted in-flight calls to UNKNOWN"
            )
        return

    # Non-durable server: reconnect is a NEW logical stream, never a continuation.
    # Any call issued before the drop is now unobservable via SSE.
    _demote_gap_spanning_calls(session)
    # Do NOT raise here: this is expected behavior, but the caller MUST
    # re-establish elicitation handling and poll/re-issue UNKNOWN calls.
    if first_received_id != expected:
        # Even as a new stream, a fresh counter restarting at 1 is fine,
        # but we record that no replay occurred so the loop cannot trust IDs.
        session.last_acked_event_id = 0


def _demote_gap_spanning_calls(session: Session) -> None:
    for call in session.calls.values():
        if call.state is CallState.PENDING:
            call.state = CallState.UNKNOWN


def recover_unknown_calls(session: Session, issue_fn) -> None:
    """
    Re-issue every UNKNOWN call idempotently. issue_fn must be safe to call
    twice with the same idempotency_key (server dedupes).
    """
    for call in session.calls.values():
        if call.state is CallState.UNKNOWN:
            if not call.idempotency_key:
                # Refuse to re-issue a non-idempotent call blindly.
                raise ResumptionIntegrityError(
                    f"call {call.request_id} is UNKNOWN and has no idempotency "
                    f"key; cannot safely re-issue after stream gap"
                )
            issue_fn(call.request_id, call.idempotency_key)
            call.state = CallState.PENDING
