# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-elicitation-response-arriving-on-a-resumed-sse-stream-as-unsolicited-rather-than-as-the-reply-to-its-o.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-mcp-elicitation-response-arriving-on-a-resumed-sse-stream-as-unsolicited-rather-than-as-the-reply-to-its-o.warrant.json
# Markdown SHA-256:   378ceae1ca6a5d08b70b70a269541f06de34b13af750ec5b1de10810ac085832
# Code AST SHA-256:   669211d71a2103260ffdc1e8dfdd5858f4bc95405e4ada0a045774ea1b7fc73a
# Verified Classes:   ElicitationCorrelationError, SlotState, ElicitationSlot, ResumedStream
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ElicitationCorrelationError(RuntimeError):
    """Raised when an elicitation cannot be safely correlated to a local slot."""


class SlotState(Enum):
    AWAITING_ANSWER = "awaiting_answer"
    ANSWER_SENT_UNACKED = "answer_sent_unacked"
    ANSWERED = "answered"
    PENDING_RECONCILE = "pending_reconcile"


@dataclass
class ElicitationSlot:
    request_id: str
    created_at_event: int          # SSE event id watermark at slot creation
    answer_epoch: int = 0
    state: SlotState = SlotState.AWAITING_ANSWER
    cached_answer: Optional[dict] = None


@dataclass
class ResumedStream:
    last_event_id: int
    outstanding: dict[str, ElicitationSlot] = field(default_factory=dict)

    def handle_incoming(
        self, request_id: str, event_id: int, payload: dict
    ) -> Optional[dict]:
        """Return an answer dict to POST, or None if reconciliation is required."""
        slot = self.outstanding.get(request_id)

        if slot is None:
            # No local slot: unsolicited or post-cold-start replay.
            # Must NOT silently drop; must NOT answer as if fresh.
            raise ElicitationCorrelationError(
                f"unsolicited elicitation {request_id!r} at event {event_id}; "
                "no matching slot, refusing to answer as fresh"
            )

        if event_id <= slot.created_at_event:
            # Transport-level replay of a request we already know about.
            if slot.state is SlotState.ANSWERED and slot.cached_answer is not None:
                return slot.cached_answer            # idempotent re-POST
            if slot.state is SlotState.ANSWER_SENT_UNACKED:
                # Ack lost: do not re-prompt, re-POST same epoch, reconcile.
                slot.state = SlotState.PENDING_RECONCILE
                return None
            # AWAITING_ANSWER but replay arrived first: treat as fresh prompt.
            return self._prompt_and_record(slot, payload)

        if event_id > slot.created_at_event:
            # Same id, later event: server reused the id. Protocol violation.
            raise ElicitationCorrelationError(
                f"elicitation id {request_id!r} reused at event {event_id} "
                f"(slot created at {slot.created_at_event}); refusing to answer"
            )

        raise ElicitationCorrelationError(
            f"unreachable correlation state for {request_id!r}"
        )

    def _prompt_and_record(
        self, slot: ElicitationSlot, payload: dict
    ) -> dict:
        answer = {"value": "user-provided"}  # stand-in for real prompt
        slot.answer_epoch += 1
        slot.cached_answer = answer
        slot.state = SlotState.ANSWER_SENT_UNACKED
        return answer


def resume_and_dispatch(stream: ResumedStream, events: list[tuple[str, int, dict]]):
    for request_id, event_id, payload in events:
        try:
            answer = stream.handle_incoming(request_id, event_id, payload)
        except ElicitationCorrelationError:
            # Surface to server as explicit error so its pending table releases.
            yield ("elicitation/error", request_id, -32600)
            continue
        if answer is None:
            yield ("elicitation/reconcile", request_id, "pending")
        else:
            yield ("elicitation/reply", request_id, answer)
