# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-mcp-streamable-http-last-event-id-resumption-when-a-stateless-tool-call-was-already-committed-server-side-but-its-sse-eve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-mcp-streamable-http-last-event-id-resumption-when-a-stateless-tool-call-was-already-committed-server-side-but-its-sse-eve.warrant.json
# Markdown SHA-256:   ffc6893d44cf8b249bf2b94f677bcd111538999e5e08fd25a0afb4401aead471
# Code AST SHA-256:   d4e1403ade96aff9cff8f077cf3b38a6ac1f46533417303af3304222ea79b77b
# Verified Classes:   ResumptionIntegrityError, RequestState, InFlightRequest, StatelessToolSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionIntegrityError(RuntimeError):
    """Raised when a resumed MCP stream cannot prove the fate of an in-flight request."""


class RequestState(Enum):
    PENDING = "pending"
    RESULT_RECEIVED = "result_received"
    FAILED = "failed"
    UNKNOWN = "unknown"  # transport interrupted after send, before result event


@dataclass
class InFlightRequest:
    request_id: str
    tool: str
    args_digest: str
    state: RequestState = RequestState.PENDING
    dispatched_at: float = field(default_factory=time.time)
    result_event_id: Optional[str] = None


class StatelessToolSession:
    """Client-side session that refuses to conflate transport resumption with exactly-once intent."""

    NON_IDEMPOTENT_TOOLS = frozenset({"git_commit", "send_email", "create_ticket", "transfer_funds"})

    def __init__(self, session_id: str, server_dedups_by_request_id: bool, replay_buffer_bound: int):
        self.session_id = session_id
        self.server_dedups = server_dedups_by_request_id
        self.replay_buffer_bound = replay_buffer_bound
        self.inflight: dict[str, InFlightRequest] = {}
        self.last_seen_event_id: Optional[str] = None

    def dispatch(self, request_id: str, tool: str, args: dict) -> InFlightRequest:
        digest = hashlib.sha256(repr(sorted(args.items())).encode()).hexdigest()[:16]
        req = InFlightRequest(request_id=request_id, tool=tool, args_digest=digest)
        # Persist PENDING *before* the network send. If this raises, we never sent.
        self.inflight[request_id] = req
        return req

    def on_transport_error(self, request_id: str) -> None:
        req = self.inflight.get(request_id)
        if req is None:
            return
        if req.state is RequestState.PENDING:
            # We sent it, we never saw the result event. This is UNKNOWN, not FAILED.
            req.state = RequestState.UNKNOWN

    def on_resume(self, requested_last_event_id: str, first_replayed_event_id: Optional[str],
                  replayed_request_ids: set[str]) -> None:
        # Detect eviction: server cannot honor our resume point.
        if first_replayed_event_id is not None and first_replayed_event_id != requested_last_event_id:
            # Gap in the replay log. Any UNKNOWN request not covered by replay is unreconcilable here.
            for rid, req in self.inflight.items():
                if req.state is RequestState.UNKNOWN and rid not in replayed_request_ids:
                    raise ResumptionIntegrityError(
                        f"Replay gap: requested Last-Event-ID={requested_last_event_id} "
                        f"but server resumed at {first_replayed_event_id}; "
                        f"request {rid} ({req.tool}) is UNKNOWN with no replay coverage "
                        f"(buffer bound={self.replay_buffer_bound}). Refusing to re-dispatch."
                    )

    def retry(self, request_id: str) -> InFlightRequest:
        req = self.inflight[request_id]
        if req.state is RequestState.UNKNOWN:
            if req.tool in self.NON_IDEMPOTENT_TOOLS and not self.server_dedups:
                raise ResumptionIntegrityError(
                    f"Cannot safely retry non-idempotent tool {req.tool} for request {request_id}: "
                    f"state is UNKNOWN, server does not dedup by request id, and blind re-dispatch "
                    f"risks duplicate side effects. Reconcile externally or escalate."
                )
            # Safe path: either idempotent or server dedups; re-dispatch same request id.
            req.state = RequestState.PENDING
            req.dispatched_at = time.time()
        return req
