# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-negotiate-an-a2a-agent-card-successfully-yet-deadlock-the-task-state-machine-on-the-first-artifact-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-negotiate-an-a2a-agent-card-successfully-yet-deadlock-the-task-state-machine-on-the-first-artifact-stream.warrant.json
# Markdown SHA-256:   8c728764b82aeb7690bb2bed035bb24ce607e67b26d131c1a08af29f55068b1a
# Code AST SHA-256:   ddec2d595d2e5691340f8ea9151530d602b36a4ae46f29bb1d01640692d63ebb
# Verified Classes:   IncompleteStreamError, State, TaskLifecycle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class IncompleteStreamError(RuntimeError):
    """Raised when an SSE artifact stream ends without a terminal TaskStatusUpdateEvent.

    Distinct from TaskNotFound: the server may still hold the task in `working`.
    Retrying with the same taskId is unsafe until tasks/get reconciles state.
    """


class State(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


TERMINAL = {State.COMPLETED, State.FAILED, State.CANCELED}


@dataclass
class TaskLifecycle:
    task_id: str
    idle_timeout_s: float = 30.0
    state: State = State.SUBMITTED
    artifact_buffer: list[str] = field(default_factory=list)
    _last_frame_at: float = field(default_factory=time.monotonic)
    _terminal_seen: bool = False

    def on_status_event(self, state: State, final: bool) -> None:
        self._last_frame_at = time.monotonic()
        # Only an explicit terminal status event may close the task.
        if state in TERMINAL and final:
            self.state = state
            self._terminal_seen = True
        elif state == State.WORKING:
            self.state = State.WORKING

    def on_artifact_event(self, text: str, last_chunk: bool) -> None:
        self._last_frame_at = time.monotonic()
        # Artifact frames are DATA, never control. last_chunk is chunking
        # metadata, not a lifecycle signal. Do not transition state here.
        self.artifact_buffer.append(text)
        if last_chunk:
            # Record intent only; do not release the slot.
            self._awaiting_terminal = True

    def check_liveness(self, now: Optional[float] = None) -> None:
        now = now or time.monotonic()
        if self._terminal_seen:
            return
        if now - self._last_frame_at > self.idle_timeout_s:
            # Fail closed. The server-side task may still be `working`;
            # caller MUST call tasks/get before any resubmit.
            raise IncompleteStreamError(
                f"task {self.task_id} stream idle {now - self._last_frame_at:.1f}s "
                f"without terminal TaskStatusUpdateEvent; "
                f"buffered {len(self.artifact_buffer)} artifact chunks; "
                f"state={self.state.value}. Reconcile via tasks/get before retry."
            )

    def release(self) -> str:
        if not self._terminal_seen:
            raise IncompleteStreamError(
                f"task {self.task_id} cannot be released: no terminal status event"
            )
        return "".join(self.artifact_buffer)


def drive_stream(lifecycle: TaskLifecycle, frames: list[dict]) -> str:
    """Consume a synthetic SSE frame list; enforce the terminal-frame invariant."""
    for frame in frames:
        kind = frame.get("event")
        data = frame.get("data", {})
        if kind == "TaskStatusUpdateEvent":
            lifecycle.on_status_event(
                State(data["status"]["state"]), data.get("final", False)
            )
        elif kind == "TaskArtifactUpdateEvent":
            art = data["artifact"]
            lifecycle.on_artifact_event(
                art["parts"][0]["text"], art.get("lastChunk", False)
            )
        else:
            raise IncompleteStreamError(
                f"task {lifecycle.task_id}: unexpected frame event={kind!r}"
            )
        lifecycle.check_liveness()
    # Stream ended. If no terminal status event arrived, fail closed.
    return lifecycle.release()


if __name__ == "__main__":
    # The observed trace: artifacts complete, no terminal status frame.
    trace = [
        {"event": "TaskStatusUpdateEvent", "data": {"status": {"state": "submitted"}, "final": False}},
        {"event": "TaskStatusUpdateEvent", "data": {"status": {"state": "working"}, "final": False}},
        {"event": "TaskArtifactUpdateEvent", "data": {"artifact": {"parts": [{"text": "part1"}], "lastChunk": False}}},
        {"event": "TaskArtifactUpdateEvent", "data": {"artifact": {"parts": [{"text": "part2"}], "lastChunk": True}}},
    ]
    lc = TaskLifecycle(task_id="t-7f3a")
    try:
        drive_stream(lc, trace)
    except IncompleteStreamError as e:
        print(f"GUARDRAIL HELD: {e}")
