# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-a2a-task-stream-after-a-terminal-artifact-was-emitted-but-before-the-client-acknowledged-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconnects-to-an-a2a-task-stream-after-a-terminal-artifact-was-emitted-but-before-the-client-acknowledged-it.warrant.json
# Markdown SHA-256:   71e1b96b5621abaf8ffbd0d0158d029117d9c2ed9d676046f2ec4e0fab25dce7
# Code AST SHA-256:   1841aaa28c500877abf6f518ab680c150ed370111636c0eada1730589533d284
# Verified Classes:   ArtifactDivergenceError, ArtifactChunk, TaskRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ArtifactDivergenceError(RuntimeError):
    """Raised when a resuming client's local artifact prefix does not match
    the server's authoritative artifact sequence. This is NOT a transient
    transport error; it means the client's buffer and the server's log have
    diverged and the local buffer must be discarded and re-fetched."""


@dataclass
class ArtifactChunk:
    chunk_id: str
    payload: bytes
    last_chunk: bool = False

    def content_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


@dataclass
class TaskRecord:
    task_id: str
    state: str  # submitted | working | input-required | completed | failed | canceled
    artifacts: list[ArtifactChunk] = field(default_factory=list)


def reconcile_on_reconnect(
    local_prefix: list[ArtifactChunk],
    server_task: TaskRecord,
) -> list[ArtifactChunk]:
    """
    Reconcile a client's local artifact prefix against the server's
    authoritative task record after a mid-stream disconnect.

    Invariant enforced: the returned artifact list is the server's full
    artifact list, and the local prefix MUST be a byte-exact prefix of it.
    If not, we raise ArtifactDivergenceError rather than silently
    concatenating a divergent suffix.
    """
    server_chunks = server_task.artifacts

    # Step 1: verify local prefix is a true prefix of the server log,
    # matching by chunk_id AND content hash (IDs alone are not sufficient;
    # a Producer may reuse an ID after regenerating a chunk).
    if len(local_prefix) > len(server_chunks):
        raise ArtifactDivergenceError(
            f"local prefix has {len(local_prefix)} chunks but server task "
            f"{server_task.task_id} only has {len(server_chunks)}"
        )

    for i, local_chunk in enumerate(local_prefix):
        server_chunk = server_chunks[i]
        if local_chunk.chunk_id != server_chunk.chunk_id:
            raise ArtifactDivergenceError(
                f"chunk {i} id mismatch: local={local_chunk.chunk_id!r} "
                f"server={server_chunk.chunk_id!r}"
            )
        if local_chunk.content_hash() != server_chunk.content_hash():
            raise ArtifactDivergenceError(
                f"chunk {i} content hash mismatch for id {local_chunk.chunk_id!r}: "
                f"producer likely regenerated this chunk after disconnect; "
                f"local buffer is divergent and must be discarded"
            )

    # Step 2: local prefix is valid; fetch only the suffix.
    suffix = server_chunks[len(local_prefix):]

    # Step 3: honor terminal state ONLY after the artifact view is complete.
    merged = list(local_prefix) + suffix
    if server_task.state == "completed":
        if not merged or not merged[-1].last_chunk:
            raise ArtifactDivergenceError(
                f"server reports task {server_task.task_id} completed but the "
                f"merged artifact view has no chunk with last_chunk=True; "
                f"terminal state cannot be honored"
            )

    return merged
