# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-server-push-elicitation-as-a-resumable-request-rather-than-a-synchronous-callback-under-http-native-strea.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-server-push-elicitation-as-a-resumable-request-rather-than-a-synchronous-callback-under-http-native-strea.warrant.json
# Markdown SHA-256:   c48ef045ec5bccef47ebec37710c7b2ca0fee07edc94513e49dc9749aa613660
# Code AST SHA-256:   934a49e3c407dd242d4acb15d926e55a9d634ac26084e2efadb39953e4d53fc9
# Verified Classes:   ElicitationRoutingError, PendingAnswer, ResumableElicitationRouter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

# Methods whose handlers may transitively invoke an LLM or unbounded external call.
# These MUST be routed to the resumable path under HTTP-native streaming.
RESUMABLE_METHODS = frozenset({"sampling/createMessage", "elicitation/create"})

# Control-plane methods safe for synchronous callback (bounded handler latency).
SYNC_METHODS = frozenset({"ping", "capabilities/probe"})


class ElicitationRoutingError(RuntimeError):
    """Raised when a server-push request is routed to a connection-bound path
    that cannot survive connection churn under HTTP-native streaming."""


@dataclass
class PendingAnswer:
    request_id: str
    method: str
    answer: Optional[dict] = None
    delivered: bool = False
    created_at: float = field(default_factory=time.monotonic)


class ResumableElicitationRouter:
    def __init__(self, read_timeout_s: float, est_intermediary_idle_s: float):
        self.read_timeout_s = read_timeout_s
        self.est_intermediary_idle_s = est_intermediary_idle_s
        self.pending: dict[str, PendingAnswer] = {}

    def classify(self, method: str, stream_has_resumed: bool) -> str:
        # A resumed stream has already lost connection identity once; never
        # trust a synchronous callback on it.
        if stream_has_resumed:
            return "resumable"
        if method in RESUMABLE_METHODS:
            return "resumable"
        if method in SYNC_METHODS:
            horizon = min(self.read_timeout_s, self.est_intermediary_idle_s)
            if horizon <= 0:
                raise ElicitationRoutingError(
                    f"no valid connection horizon for sync method {method!r}"
                )
            return "sync"
        # Unknown method: default to resumable. Unknown handlers may be slow.
        return "resumable"

    def on_request(self, request_id: str, method: str, stream_has_resumed: bool) -> str:
        route = self.classify(method, stream_has_resumed)
        if route == "resumable":
            if request_id in self.pending:
                # Duplicate delivery after resume; do not re-dispatch the handler.
                return "resumable-dedup"
            self.pending[request_id] = PendingAnswer(request_id, method)
            return "resumable"
        return "sync"

    def record_answer(self, request_id: str, answer: dict) -> None:
        entry = self.pending.get(request_id)
        if entry is None:
            # Answer arrived for a request we never registered, or already
            # completed and pruned. Treat as duplicate; do not re-derive.
            raise ElicitationRoutingError(
                f"answer for unknown request {request_id!r}; "
                f"refusing to re-invoke handler"
            )
        entry.answer = answer

    def drain_to(self, live_stream_id: str) -> list[tuple[str, dict]]:
        """Return answers to write to the currently-live stream. Idempotent:
        an answer is marked delivered only after the write is acknowledged."""
        out = []
        for entry in self.pending.values():
            if entry.answer is not None and not entry.delivered:
                out.append((entry.request_id, entry.answer))
        return out

    def on_write_ack(self, request_id: str) -> None:
        entry = self.pending.get(request_id)
        if entry is not None:
            entry.delivered = True

    def enforce_invariant(self) -> None:
        # Guardrail: any resumable-method request must have a durable entry.
        for entry in self.pending.values():
            if entry.method in RESUMABLE_METHODS and entry.answer is None:
                # Outstanding; fine. The invariant is about existence, not completion.
                continue
        # Detect the specific violation: a resumable request that was routed
        # to sync (i.e., never entered self.pending).
        for req_id, entry in self.pending.items():
            if entry.method in RESUMABLE_METHODS and entry.delivered is False and entry.answer is None:
                raise ElicitationRoutingError(
                    f"resumable request {req_id!r} has no answer and no live "
                    f"carrier; connection-bound routing would discard it"
                )
