# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-session-resumption-as-an-at-least-once-replay-hazard-rather-than-an-exactly-once-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-session-resumption-as-an-at-least-once-replay-hazard-rather-than-an-exactly-once-continuation.warrant.json
# Markdown SHA-256:   074f75b21629a8d4f86398d506304aff7f0646afea2a762bf037172bafb8d926
# Code AST SHA-256:   2e6ddd5dfa4814ce1ba29125d472a16eeb626534e8e152b3fdcfc217ec415876
# Verified Classes:   ResumptionPolicyError, StreamKind, StreamKey, McpSessionClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ResumptionPolicyError(RuntimeError):
    """Raised when a client attempts an unsafe resume/recover transition."""


class StreamKind(str, Enum):
    POST = "post"      # response stream scoped to one request
    GET = "get"        # standalone server->client stream


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

    def cursor_key(self) -> Tuple[str, StreamKind, Optional[str]]:
        return (self.session_id, self.kind, self.request_id)


@dataclass
class McpSessionClient:
    session_id: str
    # cursor per (session, stream-kind, request-id) -- enforces C1
    cursors: Dict[Tuple[str, StreamKind, Optional[str]], str] = field(default_factory=dict)
    # request ids whose server->client side effects were already applied
    applied_events: Set[str] = field(default_factory=set)
    # idempotency keys for side-effecting requests -- enforces C3
    idempotency_keys: Dict[str, str] = field(default_factory=dict)
    session_terminated: bool = False

    def idempotency_key_for(self, request_id: str, payload: bytes) -> str:
        if request_id not in self.idempotency_keys:
            self.idempotency_keys[request_id] = hashlib.sha256(
                f"{self.session_id}:{request_id}:".encode() + payload
            ).hexdigest()
        return self.idempotency_keys[request_id]

    def on_stream_dropped(self, key: StreamKey) -> None:
        if self.session_terminated:
            raise ResumptionPolicyError(
                f"cannot resume stream {key} under terminated session {self.session_id}"
            )
        # resume: reconnect same stream with its own cursor. Never re-POST.
        cursor = self.cursors.get(key.cursor_key())
        if cursor is None:
            # No cursor yet: nothing was delivered, safe to (re)open without replay.
            return

    def on_resume_rejected(self, key: StreamKey) -> str:
        """Server signalled replay-impossible (C2b). Return required action."""
        if key.kind is StreamKind.GET:
            # Accept the gap; re-sync via explicit reads; keep session alive.
            return "resync_via_reads"
        # POST stream replay impossible: request was delivered, outcome unknown.
        if key.request_id is None:
            raise ResumptionPolicyError("POST stream missing request id")
        if key.request_id not in self.idempotency_keys:
            # No idempotency key -> re-issue would double-execute. Forbid.
            raise ResumptionPolicyError(
                f"request {key.request_id} indeterminate and not idempotent; "
                "refusing to re-issue (would cause at-least-once re-execution)"
            )
        return "reconcile_indeterminate"

    def on_session_terminated(self) -> None:
        self.session_terminated = True
        self.cursors.clear()  # cursors are session-scoped; discard on death

    def apply_server_event(self, key: StreamKey, event_id: str, handler) -> None:
        """Dedupe replayed events before applying side effects -- guards sampling/elicitation."""
        if event_id in self.applied_events:
            return
        handler()
        self.applied_events.add(event_id)
        self.cursors[key.cursor_key()] = event_id


def recover_after_drop(client: McpSessionClient, key: StreamKey) -> str:
    """Single entry point the transport error handler must call."""
    if client.session_terminated:
        # Recovery path: new handshake is legitimate here.
        return "rehandshake_new_session"
    try:
        client.on_stream_dropped(key)
    except ResumptionPolicyError as exc:
        raise ResumptionPolicyError(f"resume refused: {exc}") from exc
    # Caller then attempts resume; if server rejects, call on_resume_rejected.
    return "resume_same_stream"
