# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-sse-replay-state-when-an-mcp-http-native-transport-upgrades-to-websocket-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-sse-replay-state-when-an-mcp-http-native-transport-upgrades-to-websocket-mid-session.warrant.json
# Markdown SHA-256:   ac19246880d347a2eaef19921ab5877deae7ac52c0a2330bc866db201ed3f102
# Code AST SHA-256:   75d2cc14ac412fb1c8ac6117e2e9257e9aa8986aaf698142baa36464855d2de7
# Verified Classes:   CrossNamespaceReplayError, CallOutcome, StepLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CrossNamespaceReplayError(RuntimeError):
    """Raised when an SSE resume cursor cannot be trusted across a transport upgrade."""
    pass


class CallOutcome(Enum):
    PENDING = "pending"
    COMPLETED = "completed"
    UNKNOWN = "unknown"  # sent, no acknowledged result, transport boundary crossed


@dataclass
class StepLedger:
    session_id: str
    # keyed by (step_index, tool, args_hash) -> outcome; never keyed by event id
    entries: dict = field(default_factory=dict)

    def key(self, step_index: int, tool: str, args: dict) -> tuple:
        args_hash = hashlib.sha256(
            repr(sorted(args.items())).encode()
        ).hexdigest()[:16]
        return (step_index, tool, args_hash)

    def record(self, step_index: int, tool: str, args: dict, outcome: CallOutcome):
        self.entries[self.key(step_index, tool, args)] = outcome

    def outcome(self, step_index: int, tool: str, args: dict) -> Optional[CallOutcome]:
        return self.entries.get(self.key(step_index, tool, args))


def resume_after_upgrade(
    ledger: StepLedger,
    last_event_id: int,
    upgrade_response_headers: dict,
    replayed_first_event_id: int,
    frames_emitted_during_upgrade: int,
) -> None:
    """
    Decide whether the SSE Last-Event-ID cursor is trustworthy across a
    mid-session SSE->WebSocket upgrade. Raises if the cursor is a lie.
    """
    continuity_token = upgrade_response_headers.get("Mcp-Event-Cursor")

    # Guard 1: no server-asserted cursor continuity across the boundary.
    if continuity_token is None:
        # The transport gave us no basis to map SSE ids to WS frame order.
        # Any replay is untrustworthy; force reconciliation path.
        for (step_index, tool, args_hash), outcome in list(ledger.entries.items()):
            if outcome is CallOutcome.PENDING:
                ledger.entries[(step_index, tool, args_hash)] = CallOutcome.UNKNOWN
        raise CrossNamespaceReplayError(
            f"session={ledger.session_id}: upgrade to WebSocket carried no "
            f"Mcp-Event-Cursor; Last-Event-ID={last_event_id} cannot be mapped "
            f"to {frames_emitted_during_upgrade} WS frames. "
            f"Marked in-flight calls UNKNOWN; re-drive via idempotency keys."
        )

    # Guard 2: replay must be strictly forward of our durable cursor.
    if replayed_first_event_id <= last_event_id:
        raise CrossNamespaceReplayError(
            f"session={ledger.session_id}: replay began at id "
            f"{replayed_first_event_id} <= Last-Event-ID {last_event_id}; "
            f"duplicate replay detected, refusing to advance step state."
        )

    # Guard 3: continuity token must agree with the replay start.
    if int(continuity_token) != replayed_first_event_id - 1:
        raise CrossNamespaceReplayError(
            f"session={ledger.session_id}: continuity token {continuity_token} "
            f"inconsistent with replay start {replayed_first_event_id}."
        )
    # Cursor is trustworthy; safe to replay forward.
