# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-tool-call-ledger-when-a-resumable-sse-session-is-upgraded-to-streamable-http-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-mcp-tool-call-ledger-when-a-resumable-sse-session-is-upgraded-to-streamable-http-mid-stream.warrant.json
# Markdown SHA-256:   63cf2c7df81990d89a6c6bdec171d6e45fbdb42764ac6ce284438f8c2b8acae2
# Code AST SHA-256:   b60642ec86654b59374fa4ad2b8c23c955be57bd3e4a2dca1135c955db9595fe
# Verified Classes:   LedgerDiscontinuityError, Transport, OpState, Operation, RequestLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class LedgerDiscontinuityError(RuntimeError):
    """Raised when a transport upgrade would fork or orphan the request ledger."""


class Transport(Enum):
    SSE = "sse"
    STREAMABLE_HTTP = "streamable_http"


class OpState(Enum):
    SENT_UNACK = "sent_unacknowledged"
    RESULT_RECEIVED = "result_received"
    ORPHANED = "orphaned"


@dataclass
class Operation:
    operation_id: str
    jsonrpc_id: int
    transport: Transport
    state: OpState = OpState.SENT_UNACK
    result: Optional[dict] = None


@dataclass
class RequestLedger:
    operations: dict[str, Operation] = field(default_factory=dict)
    last_sse_event_id: int = 0

    def dispatch(self, transport: Transport, jsonrpc_id: int) -> Operation:
        op = Operation(
            operation_id=str(uuid.uuid4()),
            jsonrpc_id=jsonrpc_id,
            transport=transport,
        )
        self.operations[op.operation_id] = op
        return op

    def acknowledge(self, operation_id: str, result: dict) -> None:
        op = self.operations[operation_id]
        if op.state is OpState.RESULT_RECEIVED:
            # Idempotent re-ack: same operation_id delivered twice across legs.
            if op.result != result:
                raise LedgerDiscontinuityError(
                    f"operation {operation_id} acknowledged with divergent results "
                    f"across transports; ledger cannot reconcile"
                )
            return
        op.state = OpState.RESULT_RECEIVED
        op.result = result

    def assert_upgrade_safe(self, target: Transport) -> None:
        """Called before switching transports. Enforces the upgrade invariant."""
        unacked = [
            op for op in self.operations.values()
            if op.state is OpState.SENT_UNACK
        ]
        if not unacked:
            return
        # Unacked operations exist. Safe only if they are all on the *source*
        # leg and the upgrade carries a resume cursor that can replay them.
        cross_transport = [op for op in unacked if op.transport is target]
        if cross_transport:
            raise LedgerDiscontinuityError(
                f"upgrade to {target.value} blocked: "
                f"{len(cross_transport)} operation(s) already dispatched on "
                f"target transport with no acknowledgement; ledger would fork"
            )
        if self.last_sse_event_id == 0:
            raise LedgerDiscontinuityError(
                f"upgrade to {target.value} blocked: "
                f"{len(unacked)} unacknowledged operation(s) on SSE leg but no "
                f"Last-Event-ID cursor to carry forward; replay is impossible"
            )

    def reconcile_on_upgrade(self, target: Transport, server_status: dict[str, dict]) -> None:
        """Explicit reconciliation: resolve every unacked op before proceeding."""
        self.assert_upgrade_safe(target)
        for op in list(self.operations.values()):
            if op.state is not OpState.SENT_UNACK:
                continue
            status = server_status.get(op.operation_id)
            if status is None:
                op.state = OpState.ORPHANED
                raise LedgerDiscontinuityError(
                    f"operation {op.operation_id} (jsonrpc {op.jsonrpc_id}) is "
                    f"unacknowledged on {op.transport.value} and unknown to server "
                    f"during upgrade reconciliation; orphaned, cannot proceed"
                )
            self.acknowledge(op.operation_id, status["result"])
