# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-renegotiate-the-sse-to-post-handshake-after-a-streamable-session-resume-in-mcp-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-renegotiate-the-sse-to-post-handshake-after-a-streamable-session-resume-in-mcp-http-native-transport.warrant.json
# Markdown SHA-256:   925e95ac505af6640e7ea09bf60b93ab655ee5377b326dffb95f9c513c028289
# Code AST SHA-256:   d53bef3825f226790c40a4e4c438661741f04c6fe274c649e0fb3ddde4dbe417
# Verified Classes:   StaleGenerationError, SessionState, StreamableSessionClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleGenerationError(RuntimeError):
    """Raised when a POST or response is bound to a session generation
    that no longer matches the client's current generation belief."""
    pass


@dataclass
class SessionState:
    session_id: str
    generation: int
    post_uri: str
    in_flight: Dict[int, str] = field(default_factory=dict)  # rpc_id -> generation


class StreamableSessionClient:
    def __init__(self, session_id: str, post_uri: str, generation: int = 1):
        self.state = SessionState(session_id, generation, post_uri)

    def on_sse_reconnect(self, last_event_id: int, replay: list,
                         endpoint_reeimitted: bool,
                         server_generation: Optional[int]) -> None:
        """Called on every SSE reconnect carrying Last-Event-ID.
        Decides continuity vs forced re-handshake."""
        if endpoint_reeimitted or (
            server_generation is not None
            and server_generation != self.state.generation
        ):
            # Generation rotated without our consent: fail everything in flight.
            self._fail_all_in_flight(
                reason=f"generation rotated {self.state.generation}->"
                       f"{server_generation}, endpoint_reemitted={endpoint_reeimitted}"
            )
            if server_generation is not None:
                self.state.generation = server_generation
            # Client MUST re-handshake; post_uri may be stale until re-neg.
            self._require_rehandshake()
        else:
            # Pure replay: continuity valid, in-flight calls may complete.
            pass

    def _require_rehandshake(self) -> None:
        self.state.post_uri = ""  # invalidate; no POST until endpoint re-received

    def _fail_all_in_flight(self, reason: str) -> None:
        for rpc_id in list(self.state.in_flight):
            del self.state.in_flight[rpc_id]
        if not reason:
            raise StaleGenerationError("in-flight failure without cause")

    def post_tool_call(self, rpc_id: int, payload: dict) -> None:
        if not self.state.post_uri:
            raise StaleGenerationError(
                f"POST attempted under session {self.state.session_id} "
                f"before re-handshake completed; post_uri invalidated"
            )
        self.state.in_flight[rpc_id] = self.state.generation

    def on_response(self, rpc_id: int, response_generation: Optional[int]) -> dict:
        bound = self.state.in_flight.pop(rpc_id, None)
        if bound is None:
            raise StaleGenerationError(
                f"response id={rpc_id} has no in-flight request "
                f"(late delivery from retired generation?)"
            )
        if response_generation is not None and response_generation != bound:
            raise StaleGenerationError(
                f"response id={rpc_id} generation={response_generation} "
                f"does not match bound generation={bound}; "
                f"refusing to cross-match"
            )
        return {"rpc_id": rpc_id, "generation": bound}
