# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-safe-boundary-rather-than-a-transparent-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-replay-safe-boundary-rather-than-a-transparent-reconnect.warrant.json
# Markdown SHA-256:   b31ac488b9407ffb36710725ef05dc178f21afb9a9f577f9f218effc7f9b679f
# Code AST SHA-256:   60b020e6edd80307234abaa332396ae4077703fa760fd78f3c56afa8776b8dc9
# Verified Classes:   ResumptionInvariantViolation, DispatchState, RequestRecord, SessionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ResumptionInvariantViolation(RuntimeError):
    """Raised when a client attempts to resume an MCP Streamable HTTP
    session without the durable state required to make resumption
    replay-safe (C1-C5 unmet)."""


class DispatchState(str, Enum):
    SENT = "sent"
    TERMINAL_SEEN = "terminal_seen"
    APPLIED = "applied"


@dataclass
class RequestRecord:
    jsonrpc_id: int
    method: str
    args_hash: str
    state: DispatchState = DispatchState.SENT
    last_event_id: Optional[str] = None


@dataclass
class SessionLedger:
    session_id: str
    records: dict = field(default_factory=dict)
    answered_server_requests: dict = field(default_factory=dict)
    replay_capable: Optional[bool] = None  # C3: probed or documented
    durable: bool = False  # C1: survives restart

    def idempotency_key(self, jsonrpc_id: int, args: dict) -> str:
        h = hashlib.sha256(
            json.dumps(args, sort_keys=True).encode()
        ).hexdigest()[:16]
        return f"{self.session_id}:{jsonrpc_id}:{h}"


def decide_resume_action(
    ledger: SessionLedger, jsonrpc_id: int, replay_window_open: bool
) -> str:
    if not ledger.durable:
        raise ResumptionInvariantViolation(
            f"C1 unmet: ledger for session {ledger.session_id} is not durable; "
            "cannot distinguish dispatched from undispatched request"
        )
    rec = ledger.records.get(jsonrpc_id)
    if rec is None:
        raise ResumptionInvariantViolation(
            f"unknown request id {jsonrpc_id} in session {ledger.session_id}; "
            "poison session, do not resume (row: unknown)"
        )
    if rec.state is DispatchState.APPLIED:
        return "ignore_replayed_terminal"
    if rec.state is DispatchState.TERMINAL_SEEN:
        return "apply_from_ledger"
    # state is SENT
    if ledger.replay_capable is None:
        raise ResumptionInvariantViolation(
            f"C3 unmet: replay contract for session {ledger.session_id} unknown; "
            "cannot choose between wait and re-issue"
        )
    if ledger.replay_capable and replay_window_open:
        return "resume_stream"
    # non-replayable or window closed: re-issue with idempotency key (C4)
    return "reissue_with_dedup"


def handle_server_initiated_replay(
    ledger: SessionLedger, server_request_id: str, invoke_model
):
    if server_request_id in ledger.answered_server_requests:
        # C5: replay the stored response, do not re-invoke the model
        return ledger.answered_server_requests[server_request_id]
    response = invoke_model()
    ledger.answered_server_requests[server_request_id] = response
    return response
