# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-new-logical-tool-call-rather-than-a-continuation-and-how-does-the-resump.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-last-event-id-resumption-as-a-new-logical-tool-call-rather-than-a-continuation-and-how-does-the-resump.warrant.json
# Markdown SHA-256:   6738f54e85b5ab712b812b88fe9c005c781d4f9aa7211140b446937854d49b85
# Code AST SHA-256:   ff69905ec6d2597bcd96a1583aa89da37b540113bc6e777fdc79cfae1d0e10cb
# Verified Classes:   ResumptionStateError, CallState, ResumableToolCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionStateError(RuntimeError):
    """Raised when a client attempts an illegal resumption state transition."""
    pass


class CallState(Enum):
    PENDING = "pending"
    COMPLETED = "completed"
    FAILED = "failed"
    UNKNOWN = "unknown"  # reconnected but no terminal event observed


@dataclass
class ResumableToolCall:
    tool_name: str
    args: dict
    idempotency_key: str = field(default_factory=lambda: str(uuid.uuid4()))
    last_event_id: Optional[str] = None
    state: CallState = CallState.PENDING
    result: Optional[dict] = None

    def on_reconnect_stream_closed(self, saw_terminal_event: bool) -> None:
        """
        Called when a resumption GET stream closes. The critical invariant:
        an empty/truncated replay is NOT proof of completion. Only a terminal
        event (JSON-RPC result/error) authorizes the COMPLETED transition.
        """
        if self.state is not CallState.PENDING:
            raise ResumptionStateError(
                f"reconnect on non-pending call in state={self.state.value}"
            )

        if saw_terminal_event:
            self.state = CallState.COMPLETED
            return

        # No terminal event observed. Session may still be valid; stream buffer
        # may have been evicted. We cannot distinguish "done, buffer gone" from
        # "still running, buffer gone". Must go to UNKNOWN, never COMPLETED.
        self.state = CallState.UNKNOWN

    def require_redrive(self) -> "ResumableToolCall":
        """
        Transition UNKNOWN -> PENDING for a safe re-drive. Refuses to re-drive
        a call that already reached a terminal state, and refuses to re-drive
        without a stable idempotency key (so server-side dedup is possible).
        """
        if self.state is not CallState.UNKNOWN:
            raise ResumptionStateError(
                f"re-drive only legal from UNKNOWN, got {self.state.value}"
            )
        if not self.idempotency_key:
            raise ResumptionStateError(
                "cannot re-drive without idempotency key; duplicate side effects possible"
            )
        self.state = CallState.PENDING
        self.last_event_id = None
        return self


def handle_resumption(call: ResumableToolCall, replay_events: list[dict]) -> ResumableToolCall:
    """
    replay_events: events received on the reconnect GET. Empty list means the
    server replayed nothing (buffer evicted or stream finalized). We must not
    infer completion from emptiness.
    """
    saw_terminal = any(
        e.get("event") in ("result", "error") or "result" in e or "error" in e
        for e in replay_events
    )
    call.on_reconnect_stream_closed(saw_terminal_event=saw_terminal)

    if call.state is CallState.UNKNOWN:
        # Explicit, auditable escalation rather than silent false-success.
        raise ResumptionStateError(
            f"resumption for tool={call.tool_name} key={call.idempotency_key} "
            f"last_event_id={call.last_event_id} yielded no terminal event; "
            f"call state is UNKNOWN — must re-drive with idempotency key"
        )
    return call
