# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-cross-vendor-artifact-corruption-when-taskartifactupdateevent-frames-arrive-after-terminal-taskstatusupdateevent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-cross-vendor-artifact-corruption-when-taskartifactupdateevent-frames-arrive-after-terminal-taskstatusupdateevent.warrant.json
# Markdown SHA-256:   3526fed78a42a1466b469daef3ca0ad72e8a9001ed1e1ac8977027cca5abe40d
# Code AST SHA-256:   5a1dc4676143b3a09fe2b1efb7a769d89c2e936937d905c57404d6fb1598dc51
# Verified Classes:   ArtifactTruncationError, ArtifactAccumulator, TaskDrainer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ArtifactTruncationError(RuntimeError):
    """Raised when a task reaches terminal status but an artifact never receives lastChunk."""
    pass


@dataclass
class ArtifactAccumulator:
    artifact_id: str
    chunks: list = field(default_factory=list)
    sealed: bool = False
    last_frame_at: float = field(default_factory=time.monotonic)

    def accept(self, frame: dict) -> None:
        if self.sealed:
            # append=False after seal is a correction reordered behind terminal status.
            # Do not silently overwrite; surface for replay.
            raise ArtifactTruncationError(
                f"artifact {self.artifact_id!r} received frame after seal "
                f"(append={frame.get('append')}); refusing to overwrite persisted version"
            )
        self.chunks.append(frame.get("parts", []))
        self.last_frame_at = time.monotonic()
        if frame.get("lastChunk"):
            self.sealed = True


class TaskDrainer:
    def __init__(self, settle_ms: int = 2000):
        self.settle_s = settle_ms / 1000.0
        self.artifacts: dict[str, ArtifactAccumulator] = {}
        self.status_terminal = False

    def on_artifact_frame(self, frame: dict) -> None:
        aid = frame["artifactId"]
        acc = self.artifacts.setdefault(aid, ArtifactAccumulator(aid))
        acc.accept(frame)

    def on_status_frame(self, frame: dict) -> None:
        if frame.get("final") and frame.get("state") in ("completed", "failed", "canceled"):
            # NOTE: do NOT seal artifacts here. Status is a hint, not a barrier.
            self.status_terminal = True

    def artifacts_settled(self, now: float | None = None) -> bool:
        now = now if now is not None else time.monotonic()
        for acc in self.artifacts.values():
            if acc.sealed:
                continue
            if now - acc.last_frame_at < self.settle_s:
                return False  # still draining
        return True

    def finalize(self) -> dict[str, list]:
        if not self.status_terminal:
            raise ArtifactTruncationError("finalize called before terminal status")
        if not self.artifacts_settled():
            raise ArtifactTruncationError(
                "terminal status observed but artifacts still draining; "
                "caller must poll artifacts_settled() or resubscribe"
            )
        unsealed = [a.artifact_id for a in self.artifacts.values() if not a.sealed]
        if unsealed:
            raise ArtifactTruncationError(
                f"settle window expired with unsealed artifacts: {unsealed}"
            )
        return {aid: acc.chunks for aid, acc in self.artifacts.items()}
