# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-elicitation-warrants-across-sse-resumption-behind-a-stateless-mcp-gateway.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-elicitation-warrants-across-sse-resumption-behind-a-stateless-mcp-gateway.warrant.json
# Markdown SHA-256:   1a6d309a70d9f181352b1642f112f523bfa2a4b8bd247de0cb14948753bcf426
# Code AST SHA-256:   2196d6654073c1793336f96a98aa522d6dcc56c3acc085ae5378e96f1093e3c0
# Verified Classes:   ElicitationWarrantError, ElicitationContext, WarrantStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ElicitationWarrantError(RuntimeError):
    """Raised when an elicitation response cannot be bound to a live warrant."""
    pass


@dataclass
class ElicitationContext:
    request_id: str
    incarnation: int
    session_id: str
    created_at: float
    resolved: bool = False


@dataclass
class WarrantStore:
    """Externalized pending_elicitations keyed by (session_id, request_id, incarnation)."""
    _bindings: dict[tuple[str, str, int], ElicitationContext] = field(default_factory=dict)
    _answered: set[tuple[str, str, int]] = field(default_factory=set)

    def mint(self, session_id: str, request_id: str, incarnation: int) -> ElicitationContext:
        key = (session_id, request_id, incarnation)
        if key in self._bindings:
            raise ElicitationWarrantError(
                f"duplicate mint for {key}; request_id reuse across incarnations"
            )
        ctx = ElicitationContext(request_id, incarnation, session_id, time.time())
        self._bindings[key] = ctx
        return ctx

    def resolve(self, session_id: str, request_id: str, incarnation: int) -> ElicitationContext:
        key = (session_id, request_id, incarnation)
        ctx: Optional[ElicitationContext] = self._bindings.get(key)
        if ctx is None:
            # The exact stateless-gateway failure: response landed on a backend
            # that never minted the binding, or the binding was lost on redeploy.
            raise ElicitationWarrantError(
                f"no live warrant for {key}; response orphaned "
                f"(stateless routing or lost pending map)"
            )
        if key in self._answered:
            # Replay after SSE resumption re-emitted the frame; treat as idempotent no-op.
            raise ElicitationWarrantError(
                f"warrant {key} already answered; replayed elicitation must be deduped"
            )
        self._answered.add(key)
        ctx.resolved = True
        return ctx


def handle_elicitation_response(
    store: WarrantStore,
    session_id: str,
    request_id: str,
    incarnation: int,
    payload: dict,
) -> None:
    """Entry point for POST /mcp/message carrying an elicitation response.

    Enforces the warrant-continuity invariant: the response must bind to a
    warrant minted on the same (session, request, incarnation) triple, and must
    be answered exactly once.
    """
    try:
        ctx = store.resolve(session_id, request_id, incarnation)
    except ElicitationWarrantError as exc:
        # Do NOT silently 202. Surface the orphan so the agent can re-elicit
        # rather than hang the dependent tool call.
        raise ElicitationWarrantError(
            f"elicitation {request_id} could not be resolved on this backend: {exc}"
        ) from exc

    if not isinstance(payload.get("confirm"), bool):
        raise ElicitationWarrantError(
            f"elicitation {request_id} response violates requestedSchema"
        )

    # Only here is the gated side effect permitted to proceed.
    _apply_confirmed_action(ctx, payload["confirm"])


def _apply_confirmed_action(ctx: ElicitationContext, confirm: bool) -> None:
    if not confirm:
        return
    # side effect elided
    return
