# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-elicitation-request-as-un-resumable-across-an-sse-reconnect-and-how-does-the-last-event-id-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-elicitation-request-as-un-resumable-across-an-sse-reconnect-and-how-does-the-last-event-id-cursor.warrant.json
# Markdown SHA-256:   4951e75355b89595eb0fabc66df1e3b0b108d2ebbc708a06761b89486b29c132
# Code AST SHA-256:   0ed6d7bedd453b68ff40e647d89db01c4e06acd5abdf330ec024762c788f90a3
# Verified Classes:   ElicitationReplayViolation, ElicitationRecord, ResumableClient
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Literal


class ElicitationReplayViolation(RuntimeError):
    """Raised when a replayed server-initiated request is treated as live."""
    pass


@dataclass
class ElicitationRecord:
    id: str
    state: Literal["pending", "responded", "orphaned"]


@dataclass
class ResumableClient:
    posted_elicitation_ids: set[str] = field(default_factory=set)
    seen_elicitation_ids: set[str] = field(default_factory=set)

    def on_replayed_event(self, event: dict) -> dict:
        method = event.get("method", "")
        req_id = event.get("id")

        # Notifications: replay-safe, deliver idempotently.
        if method.startswith("notifications/"):
            return {"action": "deliver", "id": req_id}

        # Server-initiated requests: replay is NOT safe to auto-respond.
        if method in ("elicitation/create", "sampling/createMessage", "roots/list"):
            if req_id in self.posted_elicitation_ids:
                # We already responded to this id before the reconnect.
                # Replay is a zombie; do not re-prompt, do not re-POST.
                return {
                    "action": "drop_zombie",
                    "id": req_id,
                    "reason": "already_posted_pre_reconnect",
                }
            if req_id in self.seen_elicitation_ids:
                # Seen but never posted: ambiguous. Probe liveness.
                return {"action": "liveness_probe", "id": req_id}

            # First observation on this connection: treat as live.
            self.seen_elicitation_ids.add(req_id)
            return {"action": "surface_to_user", "id": req_id}

        return {"action": "ignore", "id": req_id}

    def submit_elicitation_result(self, req_id: str, result: dict) -> dict:
        if req_id not in self.seen_elicitation_ids:
            raise ElicitationReplayViolation(
                f"POST for elicitation {req_id!r} never observed on stream; "
                "refusing to send a response the server cannot correlate"
            )
        # Mark BEFORE the network call so a crash mid-POST still records intent.
        self.posted_elicitation_ids.add(req_id)
        return {"posted": True, "id": req_id, "result": result}


def reconcile_replay(client: ResumableClient, replayed_events: list[dict]) -> list[dict]:
    outcomes = []
    for ev in replayed_events:
        decision = client.on_replayed_event(ev)
        outcomes.append(decision)
        if decision["action"] == "drop_zombie":
            # The tool handler already returned CANCELLED server-side.
            # Surface this to the agent so it re-plans against reality.
            outcomes.append({
                "action": "emit_tool_result",
                "id": decision["id"],
                "payload": {
                    "status": "cancelled",
                    "reason": "elicitation_orphaned_on_reconnect",
                },
            })
    return outcomes
