# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-stream-resumption-tokens-with-a-server-that-has-already-dropped-the-underlying-tool-call-frame.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-stream-resumption-tokens-with-a-server-that-has-already-dropped-the-underlying-tool-call-frame.warrant.json
# Markdown SHA-256:   a10e39cf8f6a880eddf820a110b7b865ec6ceee4380b8ebc3c499bba9e97f7ff
# Code AST SHA-256:   356b8df3883442d0c621eda2adc1dfaa0de94efc14abf80ad15776735cba276b
# Verified Classes:   ResumptionInvariantError, CallState, ResumeAck, CallTracker
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ResumptionInvariantError(RuntimeError):
    """Raised when a stream reattach cannot be proven positionally continuous."""


class CallState(Enum):
    PENDING = "pending"
    RESUMED = "resumed"
    REISSUED = "reissued"
    COMPLETE = "complete"
    FAILED = "failed"


@dataclass
class ResumeAck:
    last_event_id: int
    call_id: str


@dataclass
class CallTracker:
    call_id: str
    last_event_id: int = 0
    state: CallState = CallState.PENDING
    partial: list = field(default_factory=list)

    def reattach(self, presented_id: int, ack: Optional[ResumeAck]) -> None:
        # Guardrail: a 200 stream with no resume_ack is NOT a valid resume.
        if ack is None:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reattach to event {presented_id} "
                f"received no resume_ack; stream is positionally unverified"
            )
        if ack.call_id != self.call_id:
            raise ResumptionInvariantError(
                f"call {self.call_id}: resume_ack names call {ack.call_id}; "
                f"refusing to merge foreign event stream"
            )
        if ack.last_event_id < presented_id:
            # Server truncated its log from the front; the gap is unrecoverable.
            raise ResumptionInvariantError(
                f"call {self.call_id}: server ack {ack.last_event_id} < "
                f"presented {presented_id}; event log evicted mid-call, "
                f"must query call status out-of-band before proceeding"
            )
        if ack.last_event_id > presented_id:
            raise ResumptionInvariantError(
                f"call {self.call_id}: server ack {ack.last_event_id} > "
                f"presented {presented_id}; client lost events it never saw, "
                f"partial result is incomplete and must not be finalized"
            )
        self.state = CallState.RESUMED
        self.last_event_id = ack.last_event_id

    def reissue(self, call_dead_confirmed: bool) -> None:
        # Guardrail: never reissue a live call. Duplicate compute + last-writer-wins.
        if not call_dead_confirmed:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reissue attempted without call_dead "
                f"confirmation; a live invocation would be duplicated"
            )
        if self.state is CallState.COMPLETE:
            raise ResumptionInvariantError(
                f"call {self.call_id}: reissue after COMPLETE would overwrite "
                f"a valid result with a non-deterministic second run"
            )
        self.state = CallState.REISSUED
        self.partial.clear()
        self.last_event_id = 0  # new invocation, new ID space
