# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-mcp-streamable-http-sse-backpressure-collapse-without-silently-truncating-tool-call-results.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-mcp-streamable-http-sse-backpressure-collapse-without-silently-truncating-tool-call-results.warrant.json
# Markdown SHA-256:   38ac5960d049a986e42d4832fcd540608dc93dfb582a59cb13d2a708bda2a414
# Code AST SHA-256:   ad2dc34759bc01be9eb9f503a0397c02e34bf274a195ff3df47c31e010bae163
# Verified Classes:   SSEContinuityError, SSEEvent, ResultAssembler
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SSEContinuityError(RuntimeError):
    """Raised when an SSE-delivered tools/call result cannot be proven complete."""
    pass


@dataclass
class SSEEvent:
    event_id: int | None          # from SSE `id:` field; None means unstamped
    event_type: str               # e.g. "notifications/progress" or "result"
    payload: dict


@dataclass
class ResultAssembler:
    expected_total: int | None = None
    expected_digest: str | None = None
    chunks: dict[int, bytes] = field(default_factory=dict)
    last_id: int | None = None
    max_gap: int = 8              # replay-buffer bound; larger gap = unrecoverable

    def ingest(self, ev: SSEEvent) -> None:
        # 1. Sequence continuity check on every non-terminal event.
        if ev.event_id is not None and self.last_id is not None:
            gap = ev.event_id - self.last_id - 1
            if gap > 0:
                if gap > self.max_gap:
                    raise SSEContinuityError(
                        f"unrecoverable gap of {gap} events after id={self.last_id}; "
                        f"replay buffer bound is {self.max_gap}"
                    )
                raise SSEContinuityError(
                    f"resumable gap of {gap} events after id={self.last_id}; "
                    f"reconnect with Last-Event-ID={self.last_id}"
                )
        if ev.event_id is not None:
            self.last_id = ev.event_id

        # 2. Accumulate chunked progress payloads.
        if ev.event_type == "notifications/progress":
            idx = ev.payload["chunk_index"]
            self.chunks[idx] = ev.payload["data"].encode()

        # 3. Terminal result must commit to the emitted set.
        elif ev.event_type == "result":
            self.expected_total = ev.payload["total_chunks"]
            self.expected_digest = ev.payload["content_sha256"]

    def finalize(self) -> bytes:
        if self.expected_total is None or self.expected_digest is None:
            raise SSEContinuityError(
                "terminal result did not commit to total_chunks/content_sha256; "
                "completeness cannot be verified, refusing to admit to agent state"
            )
        missing = [i for i in range(self.expected_total) if i not in self.chunks]
        if missing:
            raise SSEContinuityError(
                f"delivered {len(self.chunks)}/{self.expected_total} chunks; "
                f"missing indices {missing[:10]}"
            )
        assembled = b"".join(self.chunks[i] for i in range(self.expected_total))
        if hashlib.sha256(assembled).hexdigest() != self.expected_digest:
            raise SSEContinuityError(
                "assembled payload digest mismatch; stream was reordered or corrupted"
            )
        return assembled
