# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-http-native-sse-stream-is-upgraded-to-websocket-mid-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-http-native-sse-stream-is-upgraded-to-websocket-mid-turn.warrant.json
# Markdown SHA-256:   aac19eb3216136a44aa281060a6153e80de7396b0f759cadc644827436ee730b
# Code AST SHA-256:   2d7207e76c6ebdc19e14be6ec008a9b2e1771d5c14e0e2bb5f5643c97cbf66de
# Verified Classes:   UpgradeCorrelationError, InflightRequest, CorrelationManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UpgradeCorrelationError(RuntimeError):
    """Raised when a mid-turn SSE->WebSocket upgrade cannot prove request continuity."""
    pass


@dataclass
class InflightRequest:
    jsonrpc_id: str
    last_event_id: int


@dataclass
class CorrelationManifest:
    cursor: int
    inflight: list[InflightRequest] = field(default_factory=list)

    def digest(self) -> str:
        payload = f"{self.cursor}|" + ",".join(
            f"{r.jsonrpc_id}@{r.last_event_id}" for r in sorted(self.inflight, key=lambda r: r.jsonrpc_id)
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def negotiate_upgrade(
    inflight: list[InflightRequest],
    peer_supports_manifest: bool,
    peer_echoed_digest: str | None,
    cursor: int,
) -> CorrelationManifest:
    """
    Decide whether a mid-turn SSE->WebSocket upgrade is safe.

    Invariant: if inflight is non-empty, the peer MUST support the correlation
    manifest and MUST echo its digest in the 101 response. Otherwise the upgrade
    is a duplicate-execution hazard and must be refused.
    """
    if not inflight:
        # Nothing pending; upgrade carries no correlation risk.
        return CorrelationManifest(cursor=cursor, inflight=[])

    if not peer_supports_manifest:
        raise UpgradeCorrelationError(
            f"refusing upgrade: {len(inflight)} in-flight RPCs but peer lacks "
            f"correlation-manifest support; drain SSE or abort turn"
        )

    manifest = CorrelationManifest(cursor=cursor, inflight=list(inflight))
    expected = manifest.digest()

    if peer_echoed_digest is None:
        raise UpgradeCorrelationError(
            "refusing upgrade: 101 response omitted manifest digest echo; "
            "cannot prove request-registry continuity across transport swap"
        )

    if peer_echoed_digest != expected:
        raise UpgradeCorrelationError(
            f"manifest digest mismatch: expected {expected[:12]}…, "
            f"peer echoed {peer_echoed_digest[:12]}…; "
            f"server registry diverged from client in-flight set"
        )

    return manifest


def dispatch_response(
    msg: dict,
    sse_pending: dict[str, object],
    ws_pending: dict[str, object],
    dedup: dict[str, str],
) -> str:
    """
    Single keyed router over JSON-RPC id. Rejects orphan responses and
    suppresses duplicates that would otherwise trigger re-execution.
    """
    rid = msg.get("id")
    if rid is None:
        raise UpgradeCorrelationError("response missing jsonrpc id; unroutable")

    if rid in dedup:
        # Already delivered on the other transport; do not re-settle or re-execute.
        return f"duplicate-suppressed:{rid}"

    target = sse_pending.pop(rid, None)
    if target is None:
        target = ws_pending.pop(rid, None)

    if target is None:
        raise UpgradeCorrelationError(
            f"orphan response id={rid}: present in neither pending map; "
            f"likely upgrade lost correlation — treat as duplicate-execution event"
        )

    dedup[rid] = "delivered"
    return f"settled:{rid}"
