# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-artifact-chunk-reassembly-as-a-state-machine-transition-rather-than-a-buffered-stream-and-why-does-the-di.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-artifact-chunk-reassembly-as-a-state-machine-transition-rather-than-a-buffered-stream-and-why-does-the-di.warrant.json
# Markdown SHA-256:   058ce76faf18b9d2d336706ad9e6234cb484ce7573b07e6e00d70dcaf756803d
# Code AST SHA-256:   ea883a8c4688f2ce78df684879a5ab8b69b1517f87ba240d1687ca19c04bdc83
# Verified Classes:   ArtifactEpochViolation, EpochScopedArtifactAssembler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ArtifactEpochViolation(RuntimeError):
    """Raised when an artifact chunk cannot be reconciled against the task-state epoch."""
    pass


class EpochScopedArtifactAssembler:
    """
    Reassembles A2A artifact chunks scoped to the task-state epoch.
    A chunk is applied only if it belongs to the buffer's current epoch;
    otherwise the buffer is discarded and reopened (regeneration).
    """

    def __init__(self):
        # taskId -> current epoch (incremented on non-'working' transitions)
        self._epoch: dict[str, int] = {}
        # (taskId, artifactId) -> {"epoch": int, "chunks": list[bytes], "sealed": bool}
        self._buffers: dict[tuple[str, str], dict] = {}

    def on_status(self, task_id: str, state: str) -> None:
        if state not in ("working",):
            self._epoch[task_id] = self._epoch.get(task_id, 0) + 1
        if state in ("failed", "canceled"):
            for key, buf in self._buffers.items():
                if key[0] == task_id:
                    buf["sealed"] = True

    def on_chunk(
        self,
        task_id: str,
        artifact_id: str,
        data: bytes,
        append: bool,
        last_chunk: bool,
    ) -> bytes | None:
        if task_id not in self._epoch:
            raise ArtifactEpochViolation(
                f"chunk for task {task_id!r} arrived before any status event; "
                f"cannot establish epoch"
            )
        epoch = self._epoch[task_id]
        key = (task_id, artifact_id)
        buf = self._buffers.get(key)

        if buf is not None and buf["sealed"]:
            raise ArtifactEpochViolation(
                f"chunk for sealed artifact {artifact_id!r} on task {task_id!r}; "
                f"task terminated and no new 'submitted' epoch was opened"
            )

        if buf is None or buf["epoch"] != epoch or not append:
            # Regeneration boundary: discard prior generation, open new buffer.
            buf = {"epoch": epoch, "chunks": [], "sealed": False}
            self._buffers[key] = buf

        buf["chunks"].append(data)

        if last_chunk:
            assembled = b"".join(buf["chunks"])
            del self._buffers[key]
            return assembled
        return None
