# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reattach-to-a-resumable-mcp-streamable-http-session-when-the-server-has-an-elicitation-request-in-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reattach-to-a-resumable-mcp-streamable-http-session-when-the-server-has-an-elicitation-request-in-flight.warrant.json
# Markdown SHA-256:   66c243d7606618ee449f9a4bd82b0233208abddbb7df059709b62885171cb5b8
# Code AST SHA-256:   575779c857a4a9409c29b075c155c1243ae3edaa51897df528ce6cb14d1b1b13
# Verified Classes:   SessionReattachError, ReattachState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SessionReattachError(RuntimeError):
    """Raised when SSE reattachment cannot guarantee request-set continuity."""


@dataclass
class ReattachState:
    session_id: str
    last_event_id: int
    outstanding_server_requests: set[int] = field(default_factory=set)
    open_tool_calls: dict[str, set[int]] = field(default_factory=dict)


def reconcile_reattach(
    state: ReattachState,
    first_replayed_seq: Optional[int],
    replayed_request_ids: set[int],
) -> ReattachState:
    """
    Given the client's durable state and the first event the server replayed
    after reconnect, decide whether the event cursor is contiguous and whether
    the outstanding-request set can be reconstructed from replay.
    """
    if first_replayed_seq is None:
        # Server replayed nothing: either no events were missed or the buffer
        # was fully evicted. We cannot distinguish, so we must re-derive.
        if state.outstanding_server_requests:
            raise SessionReattachError(
                f"session {state.session_id}: no replayed events but "
                f"{len(state.outstanding_server_requests)} server requests "
                f"still outstanding; cannot confirm elicitation delivery"
            )
        return state

    expected = state.last_event_id + 1
    if first_replayed_seq != expected:
        # Lossy replay: events between expected and first_replayed_seq were
        # evicted. Any elicitation in that gap is unrecoverable from the log.
        lost = state.outstanding_server_requests - replayed_request_ids
        if lost:
            raise SessionReattachError(
                f"session {state.session_id}: lossy replay "
                f"(expected seq {expected}, got {first_replayed_seq}); "
                f"unrecoverable elicitations {sorted(lost)} — "
                f"must re-query server pending-request table"
            )
        # No outstanding requests lost; cursor can advance but is marked lossy.
        state.last_event_id = first_replayed_seq - 1
        return state

    # Contiguous replay: events are authoritative, but the pending-request
    # table is still separate. Reconcile outstanding IDs against what replayed.
    unreconciled = state.outstanding_server_requests - replayed_request_ids
    if unreconciled:
        raise SessionReattachError(
            f"session {state.session_id}: contiguous replay but "
            f"request IDs {sorted(unreconciled)} not re-emitted; "
            f"server must resend pending elicitations with original id"
        )
    return state


def close_tool_call(state: ReattachState, call_id: str, request_ids: set[int]) -> None:
    """Only mark a tool call complete when all its elicitations resolved."""
    unresolved = request_ids & state.outstanding_server_requests
    if unresolved:
        raise SessionReattachError(
            f"session {state.session_id}: cannot close tool call {call_id}; "
            f"elicitations {sorted(unresolved)} still pending"
        )
    state.open_tool_calls.pop(call_id, None)
