# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-streamable-http-last-event-id-resume-because-the-sse-stream-it-is-resuming-was-already-reaped-by-the-server-s-session-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-streamable-http-last-event-id-resume-because-the-sse-stream-it-is-resuming-was-already-reaped-by-the-server-s-session-t.warrant.json
# Markdown SHA-256:   6a8779fbf234b7c4eb2c7c1ecf76e6136f40d93281c164ff1eb1bcf38bf5b1f0
# Code AST SHA-256:   90a752cc2ce8f09695bcc84c7dcc8aca1effa24a3973fccf4a78c741e3aef5d0
# Verified Classes:   AmbiguousResumeError, DuplicateExecutionGuard, LedgerEntry, StreamResumeClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class AmbiguousResumeError(RuntimeError):
    """Raised when a Last-Event-ID resume returns no event past the presented ID.

    This is the Trace B condition: the stream may have been reaped, and a naive
    replay would duplicate a side-effecting tool call. The caller must reconcile
    via the request ledger, not replay.
    """


class DuplicateExecutionGuard(RuntimeError):
    """Raised when the ledger shows the jsonrpc_id was already dispatched."""


@dataclass
class LedgerEntry:
    jsonrpc_id: str
    tool: str
    args_hash: str
    dispatched_at: float
    resolved: bool = False


class StreamResumeClient:
    def __init__(self, transport, ledger):
        self.transport = transport
        self.ledger = ledger

    def call_tool(self, jsonrpc_id: str, tool: str, args: dict) -> dict:
        args_hash = hashlib.sha256(repr(sorted(args.items())).encode()).hexdigest()

        # Invariant: ledger write MUST precede dispatch.
        prior = self.ledger.get(jsonrpc_id)
        if prior is not None and not prior.resolved:
            raise DuplicateExecutionGuard(
                f"jsonrpc_id {jsonrpc_id} already dispatched at {prior.dispatched_at}; "
                f"reconcile via tools/status before retry"
            )
        self.ledger.put(LedgerEntry(jsonrpc_id, tool, args_hash, time.time()))

        resp = self.transport.post_tool_call(jsonrpc_id, tool, args)
        last_event_id = resp.last_event_id

        # Mid-stream disconnect simulated by transport returning a resume token.
        while resp.needs_resume:
            resume = self.transport.resume(last_event_id)
            if resume.status == 409 and resume.reason == "stream-reaped":
                # Server told us explicitly: stream is gone. Do not replay.
                raise AmbiguousResumeError(
                    f"stream reaped for {jsonrpc_id}; tool may still be running server-side"
                )
            if resume.status == 200:
                first = resume.read_first_event(timeout=5.0)
                if first is None or first.event_id <= last_event_id:
                    # Empty or non-advancing resume: assume reaped. Safe default.
                    raise AmbiguousResumeError(
                        f"ambiguous resume for {jsonrpc_id}: no event past {last_event_id}; "
                        f"treating as reaped to avoid duplicate execution"
                    )
                last_event_id = first.event_id
                resp = resume
            else:
                raise AmbiguousResumeError(f"unexpected resume status {resume.status}")

        self.ledger.mark_resolved(jsonrpc_id)
        return resp.body
