# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-session-whose-last-event-id-cursor-was-advanced-by-a-server-side-sse-upgrade-the-client-neve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-session-whose-last-event-id-cursor-was-advanced-by-a-server-side-sse-upgrade-the-client-neve.warrant.json
# Markdown SHA-256:   4391f158b61308169c641fadc612eb349724f8d70f6af44b72ea1fba48fabff2
# Code AST SHA-256:   e5d11dd73f22fd60da9630dd2a7f97f37015c15f731d1dbabf4e6e93f4668b5d
# Verified Classes:   StreamableSessionError, CursorDivergenceError, ResumptionGapError, SessionCursor, Response
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Any, Callable, Optional


class StreamableSessionError(RuntimeError):
    """Base for streamable-session transport failures."""


class CursorDivergenceError(StreamableSessionError):
    """Client cursor lags server journal head by events the client never parsed."""


class ResumptionGapError(StreamableSessionError):
    """Server reports a gap between the client's Last-Event-ID and its retained journal."""


@dataclass
class SessionCursor:
    last_event_id: int = 0
    parsed_ids: set[int] = field(default_factory=set)

    def advance(self, event_id: int) -> None:
        # Invariant: advance only on parsed receipt; replay of a seen id is a no-op.
        if event_id in self.parsed_ids:
            return
        if event_id != self.last_event_id + 1:
            raise CursorDivergenceError(
                f"cursor jump: expected {self.last_event_id + 1}, got {event_id}"
            )
        self.parsed_ids.add(event_id)
        self.last_event_id = event_id


@dataclass
class Response:
    content_type: str
    events: list[tuple[int, dict[str, Any]]]  # (id, payload) for SSE; empty for JSON
    body: Optional[dict[str, Any]] = None


def handle_response(
    resp: Response,
    cursor: SessionCursor,
    expected_stream: bool,
    reconnect: Callable[[int], Response],
) -> dict[str, Any]:
    """Process one MCP streamable response under the receipt-gated invariant.

    expected_stream: True if the client committed to SSE before sending.
    """
    ct = resp.content_type.split(";")[0].strip().lower()

    if ct == "text/event-stream":
        if not expected_stream:
            # Server upgraded mid-response. Client may not have parsed it.
            # Do NOT advance cursor. Issue a resumption probe from last known id.
            return _resumption_probe(cursor, reconnect)
        for event_id, payload in resp.events:
            cursor.advance(event_id)
            _dispatch(payload)
        return {"ok": True, "cursor": cursor.last_event_id}

    if ct == "application/json":
        if expected_stream:
            # Client committed to stream but got JSON: server declined upgrade.
            # Safe: no journal events were emitted for this request.
            return resp.body or {}
        return resp.body or {}

    raise StreamableSessionError(f"unexpected content-type: {ct!r}")


def _resumption_probe(
    cursor: SessionCursor, reconnect: Callable[[int], Response]
) -> dict[str, Any]:
    """Reconnect from last known cursor; require explicit replay or gap signal.

    A server that returns an empty stream to a resume-from-cursor request is
    making an unsound delivery claim. Treat the session as poisoned.
    """
    resp = reconnect(cursor.last_event_id)
    ct = resp.content_type.split(";")[0].strip().lower()

    if ct == "application/json" and resp.body and "error" in resp.body:
        err = resp.body["error"]
        gap = (err.get("data") or {}).get("gap")
        if gap is not None:
            raise ResumptionGapError(
                f"server retained journal from {gap}; client cursor {cursor.last_event_id} "
                f"is unrecoverable — re-initialize session"
            )

    if ct == "text/event-stream" and not resp.events:
        raise CursorDivergenceError(
            f"server replayed zero events for Last-Event-ID={cursor.last_event_id}; "
            f"in-flight request result is unrecoverable — session poisoned"
        )

    for event_id, payload in resp.events:
        cursor.advance(event_id)
        _dispatch(payload)
    return {"ok": True, "cursor": cursor.last_event_id, "recovered": True}


def _dispatch(payload: dict[str, Any]) -> None:
    # JSON-RPC dispatch; orphaned results (no pending request) are dropped with a log.
    method = payload.get("method")
    if method is None and "id" in payload:
        # result/error for a request the client may have GC'd — log, do not raise.
        return
    return
