# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-mcp-streamable-http-session-resumption-when-server-push-notifications-and-tool-responses-interleave-on-a-single-sse-strea.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-mcp-streamable-http-session-resumption-when-server-push-notifications-and-tool-responses-interleave-on-a-single-sse-strea.warrant.json
# Markdown SHA-256:   0bbf2480d90cbd3d14cb39bc0d0b5171f3b7f037a7dc1752050222295546c52f
# Code AST SHA-256:   08ebbf8a39f33a7b9461a6e20102c17302bf33a22a9eb804d076d9c8324bae78
# Verified Classes:   ResumptionAmbiguous, StreamKind, StreamKey, StreamCursor, ResumptionManager
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ResumptionAmbiguous(RuntimeError):
    """Raised when a reconnect cannot prove stream identity and the tool is not idempotent."""


class StreamKind(Enum):
    POST = "post"   # response stream for a specific request
    GET = "get"     # standalone server-push stream


@dataclass(frozen=True)
class StreamKey:
    session_id: str
    kind: StreamKind
    request_id: Optional[str]  # None for GET


@dataclass
class StreamCursor:
    last_event_id: Optional[str] = None
    terminal_seen: bool = False


@dataclass
class ResumptionManager:
    # One cursor per stream. Never a single session-level lastEventId.
    cursors: Dict[StreamKey, StreamCursor] = field(default_factory=dict)
    idempotent_tools: frozenset = frozenset()

    def observe(self, key: StreamKey, event_id: str, terminal: bool) -> None:
        cur = self.cursors.setdefault(key, StreamCursor())
        cur.last_event_id = event_id
        if terminal:
            cur.terminal_seen = True

    def decide(
        self,
        reconnect_key: StreamKey,
        cursor_origin: StreamKey,
        tool_name: Optional[str],
    ) -> Tuple[str, Optional[str]]:
        """Return ('resume', last_event_id) or ('retry', None) or raise."""
        origin_cur = self.cursors.get(cursor_origin)

        # 1. Terminal barrier: never resume a stream that already delivered its result.
        if origin_cur is not None and origin_cur.terminal_seen:
            return ("complete", None)

        # 2. Proven same-stream resume is the only fully safe path.
        if reconnect_key == cursor_origin and origin_cur and origin_cur.last_event_id:
            return ("resume", origin_cur.last_event_id)

        # 3. Cross-stream cursor: cannot prove identity.
        if tool_name is not None and tool_name in self.idempotent_tools:
            return ("retry", None)

        raise ResumptionAmbiguous(
            f"cannot prove stream identity for reconnect {reconnect_key} "
            f"using cursor from {cursor_origin}; tool={tool_name!r} not idempotent"
        )


def resume_or_fail(
    mgr: ResumptionManager,
    reconnect_key: StreamKey,
    cursor_origin: StreamKey,
    tool_name: Optional[str],
) -> str:
    action, last_id = mgr.decide(reconnect_key, cursor_origin, tool_name)
    if action == "resume":
        return f"Last-Event-ID: {last_id}"
    if action == "retry":
        return "RETRY"
    if action == "complete":
        return "COMPLETE"
    raise ResumptionAmbiguous("unreachable decision state")
