# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-artifact-chunk-as-authoritative-versus-a-duplicate-of-a-push-notification-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-artifact-chunk-as-authoritative-versus-a-duplicate-of-a-push-notification-payload.warrant.json
# Markdown SHA-256:   96adf72975e2076d8a851af9d8c47ba77d8e7f1219f7976caf08895b7127a006
# Code AST SHA-256:   4b5c84d7041e745d8df15046f1080776770e0f63bb1a8b8389b2a94015216b5e
# Verified Classes:   ArtifactSequenceGap, ArtifactReplayDiscarded, ArtifactAssembler
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple, Optional


class ArtifactSequenceGap(RuntimeError):
    """Raised when a streamed chunk skips ahead of the durable high-water mark,
    meaning the client cannot safely assemble the artifact from stream alone."""


class ArtifactReplayDiscarded(Exception):
    """Raised (and caught) internally when a replayed chunk is correctly rejected."""
    pass


@dataclass
class ArtifactAssembler:
    # persisted across reconnects and process restarts
    high_water: Dict[Tuple[str, str], int] = field(default_factory=dict)
    buffers: Dict[Tuple[str, str], list] = field(default_factory=dict)

    def _key(self, task_id: str, artifact_id: str) -> Tuple[str, str]:
        return (task_id, artifact_id)

    def accept_chunk(
        self,
        task_id: str,
        artifact_id: str,
        chunk_seq: int,
        payload: bytes,
        event_type: str = "artifact.append",
    ) -> None:
        key = self._key(task_id, artifact_id)

        # artifact.replace resets the lineage; treat as new artifact
        if event_type == "artifact.replace":
            self.high_water[key] = chunk_seq
            self.buffers[key] = [payload]
            return

        if event_type != "artifact.append":
            raise ArtifactSequenceGap(
                f"unknown event_type={event_type!r} for {key}; refusing to assemble"
            )

        hwm = self.high_water.get(key)

        # Cold start: no durable mark. Stream chunk is advisory only.
        if hwm is None:
            raise ArtifactSequenceGap(
                f"no durable high-water mark for {key}; "
                f"must reconcile via tasks/get before accepting streamed chunks"
            )

        if chunk_seq <= hwm:
            # Replay from webhook retry or SSE resume. Correctly discard.
            raise ArtifactReplayDiscarded(
                f"replay chunk_seq={chunk_seq} <= hwm={hwm} for {key}"
            )

        if chunk_seq != hwm + 1:
            # Gap: client's hwm is wrong or a chunk was lost on both channels.
            raise ArtifactSequenceGap(
                f"gap for {key}: expected chunk_seq={hwm + 1}, got {chunk_seq}; "
                f"reconcile via tasks/get before continuing"
            )

        self.buffers.setdefault(key, []).append(payload)
        self.high_water[key] = chunk_seq

    def try_accept(self, *args, **kwargs) -> bool:
        """Convenience wrapper: returns False on replay, re-raises on gap."""
        try:
            self.accept_chunk(*args, **kwargs)
            return True
        except ArtifactReplayDiscarded:
            return False

    def reconcile_from_tasks_get(
        self,
        task_id: str,
        artifact_id: str,
        last_chunk_seq: int,
        assembled_prefix: bytes,
    ) -> None:
        """Initialize or repair the high-water mark from authoritative state."""
        key = self._key(task_id, artifact_id)
        self.high_water[key] = last_chunk_seq
        self.buffers[key] = [assembled_prefix]


def handle_stream_event(
    assembler: ArtifactAssembler,
    task_id: str,
    artifact_id: str,
    chunk_seq: int,
    payload: bytes,
    event_type: str = "artifact.append",
) -> Optional[bytes]:
    if not assembler.try_accept(
        task_id, artifact_id, chunk_seq, payload, event_type
    ):
        # replay: drop silently, do not advance buffer
        return None
    return b"".join(assembler.buffers[(task_id, artifact_id)])


def terminal_reconcile(
    assembler: ArtifactAssembler,
    task_id: str,
    artifact_id: str,
    authoritative_chunk_seq: int,
    authoritative_bytes: bytes,
) -> bytes:
    """At task terminal state, the tasks/get result wins. If the stream
    assembled a different length or seq than authoritative, the stream
    assembly is corrupt and must be discarded."""
    key = (task_id, artifact_id)
    streamed_hwm = assembler.high_water.get(key)
    streamed_len = sum(len(p) for p in assembler.buffers.get(key, []))

    if streamed_hwm is not None and streamed_hwm != authoritative_chunk_seq:
        raise ArtifactSequenceGap(
            f"stream hwm={streamed_hwm} != authoritative={authoritative_chunk_seq} "
            f"for {key}; stream assembly is corrupt, using tasks/get result"
        )
    if streamed_len != 0 and streamed_len != len(authoritative_bytes):
        raise ArtifactSequenceGap(
            f"stream length={streamed_len} != authoritative={len(authoritative_bytes)} "
            f"for {key}; suspected duplication from webhook retry"
        )

    assembler.reconcile_from_tasks_get(
        task_id, artifact_id, authoritative_chunk_seq, authoritative_bytes
    )
    return authoritative_bytes
