# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-http-session-when-the-server-push-sse-stream-reconnects-behind-an-in-flight-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-streamable-http-session-when-the-server-push-sse-stream-reconnects-behind-an-in-flight-tool-call.warrant.json
# Markdown SHA-256:   fb83ac1c3748b14b5fad47856e33ebddca31d9ffb470a2abf15a4001aebca78d
# Code AST SHA-256:   ac129c5e14d96d40fa025b093bd9c3bb2798eb6c602d4fe81a6fbc4ad86d6377
# Verified Classes:   ResumptionInvariantError, CallState, OutstandingCall, SessionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum


class ResumptionInvariantError(RuntimeError):
    """Raised when a session resume would violate request/response correlation."""


class CallState(Enum):
    IN_FLIGHT = "in_flight"
    COMPLETED = "completed"
    UNKNOWN = "unknown"  # request-channel drop, disposition indeterminate


@dataclass
class OutstandingCall:
    request_id: int
    method: str
    params_hash: str
    idempotency_key: str | None
    state: CallState = CallState.IN_FLIGHT
    result: dict | None = None

    @staticmethod
    def fingerprint(method: str, params: dict) -> str:
        blob = json.dumps({"m": method, "p": params}, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class SessionLedger:
    session_id: str
    last_event_id: int = 0
    calls: dict[int, OutstandingCall] = field(default_factory=dict)
    completed_progress_tokens: set[str] = field(default_factory=set)

    def register_call(self, request_id: int, method: str, params: dict,
                      idempotency_key: str | None) -> OutstandingCall:
        call = OutstandingCall(
            request_id=request_id,
            method=method,
            params_hash=OutstandingCall.fingerprint(method, params),
            idempotency_key=idempotency_key,
        )
        self.calls[request_id] = call
        return call


def resume_push_stream(ledger: SessionLedger, new_last_event_id: int) -> list[str]:
    """Resume the GET push stream. Pure replay: never re-issues a tools/call.

    Returns the list of progress tokens whose events must be DISCARDED because
    they belong to already-completed calls (replay of a finished invocation).
    """
    if new_last_event_id < ledger.last_event_id:
        raise ResumptionInvariantError(
            f"server replayed Last-Event-ID {new_last_event_id} behind "
            f"client cursor {ledger.last_event_id}; event ordering regressed"
        )
    ledger.last_event_id = new_last_event_id
    # Replayed progress for a completed call is stale; do not re-surface it.
    return sorted(ledger.completed_progress_tokens)


def handle_request_channel_drop(ledger: SessionLedger, request_id: int) -> CallState:
    """The POST carrying a tools/call died before its body arrived.

    Never silently re-issue a non-idempotent call. Either dedup via key or
    mark the call UNKNOWN so the agent loop halts for reconciliation.
    """
    call = ledger.calls.get(request_id)
    if call is None:
        raise ResumptionInvariantError(
            f"request {request_id} not in ledger; correlation record lost on drop"
        )
    if call.state is CallState.COMPLETED:
        return call.state
    if call.idempotency_key is not None:
        # Safe to re-issue with the same key; server must dedup.
        return CallState.IN_FLIGHT
    call.state = CallState.UNKNOWN
    raise ResumptionInvariantError(
        f"call {request_id} ({call.method}) dropped with no idempotency key; "
        "disposition indeterminate — agent loop must reconcile before continuing"
    )
