# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-duplicate-a2a-v1-0-taskstatusupdateevent-rather-than-acknowledge-it-as-an-idempotent-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-duplicate-a2a-v1-0-taskstatusupdateevent-rather-than-acknowledge-it-as-an-idempotent-replay.warrant.json
# Markdown SHA-256:   f0cee92d16634978e070c82ec9612712b2e0439c7c1ead3ad1094eea8f71f410
# Code AST SHA-256:   59dfe158b856393dae334dc6b59f6b38d95566bc8f33a3c5bfb106ec53e02430
# Verified Classes:   A2AConformanceError, EventIdReuseError, ReplayUnavailableError, StatusEvent, PendingBuffer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class A2AConformanceError(RuntimeError):
    """Raised when an A2A v1.0 status event cannot be safely acknowledged."""


class EventIdReuseError(A2AConformanceError):
    """Same eventId, divergent payload — peer violated event identity."""


class ReplayUnavailableError(A2AConformanceError):
    """Last-Event-ID references an evicted buffer entry; resync required."""


@dataclass
class StatusEvent:
    task_id: str
    event_id: str
    state: str
    final: bool
    artifact: Optional[bytes] = None
    message: Optional[str] = None

    def payload_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.state.encode())
        h.update(b"\x00")
        h.update(b"1" if self.final else b"0")
        h.update(b"\x00")
        h.update(self.artifact or b"")
        h.update(b"\x00")
        h.update((self.message or "").encode())
        return h.hexdigest()


@dataclass
class PendingBuffer:
    # Keyed by eventId, NEVER by toState.
    entries: dict[str, StatusEvent] = field(default_factory=dict)
    applied_cursor: Optional[str] = None

    def acknowledge(self, incoming: StatusEvent) -> str:
        """Return 'replay' | 'applied' | raise on violation."""
        prior = self.entries.get(incoming.event_id)

        # C1: identity match?
        if prior is not None:
            # C2: payload equivalence?
            if prior.payload_hash() != incoming.payload_hash():
                raise EventIdReuseError(
                    f"eventId={incoming.event_id} reused with divergent payload "
                    f"for taskId={incoming.task_id}"
                )
            # C3: not older than applied cursor?
            if self.applied_cursor is not None and incoming.event_id < self.applied_cursor:
                # Stale replay: re-emit current state, do not rewind.
                return "stale_replay"
            # C4: still buffered (it is, by construction of `prior`).
            return "replay"

        # C1 fails: new transition. Append and advance cursor.
        self.entries[incoming.event_id] = incoming
        self.applied_cursor = incoming.event_id
        return "applied"

    def replay_from(self, last_event_id: str) -> list[StatusEvent]:
        if last_event_id not in self.entries:
            raise ReplayUnavailableError(
                f"Last-Event-ID={last_event_id} not in buffer; "
                f"contiguity broken, client must resync via tasks/get"
            )
        ids = sorted(self.entries)
        idx = ids.index(last_event_id)
        return [self.entries[i] for i in ids[idx + 1:]]


def handle_stream_event(buf: PendingBuffer, ev: StatusEvent) -> str:
    result = buf.acknowledge(ev)
    if result == "replay":
        # Re-emit cached event; no buffer mutation.
        return "200 OK (replay)"
    if result == "stale_replay":
        return "200 OK (current state, no rewind)"
    return "200 OK (applied)"
