# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-treat-a-terminal-a2a-task-state-as-authoritative-for-artifact-streaming-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-treat-a-terminal-a2a-task-state-as-authoritative-for-artifact-streaming-negotiation.warrant.json
# Markdown SHA-256:   82673907b49b2042ddb53e3c7cb2c292e5bc43d8b1a391918b312c22c297aca9
# Code AST SHA-256:   5e416e1edbd65be8a1b73fb3e07b1fc62a213a082d126aa99b6f9b91a7338e1b
# Verified Classes:   ArtifactStreamNegotiationError, TaskState, StreamContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ArtifactStreamNegotiationError(RuntimeError):
    """Raised when terminal task state is being misused as artifact-stream authority."""
    pass


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


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


@dataclass
class StreamContext:
    streaming_advertised: bool
    is_resubscribe: bool
    artifact_final_marker_seen: bool = False
    replay_complete_marker_seen: bool = False
    artifact_event_count: int = 0
    events_after_terminal_status: int = 0


def authorize_stream_teardown(
    ctx: StreamContext,
    observed_state: TaskState,
    status_final: bool,
) -> bool:
    """
    Decide whether the client may close its artifact sink.

    Returns True only when artifact-stream finality is independently established.
    Raises ArtifactStreamNegotiationError when the situation is ambiguous and
    acting on the status event would risk silent artifact loss.
    """
    if not ctx.streaming_advertised:
        # Server violated its own Agent Card; neither status nor artifacts are trustworthy.
        raise ArtifactStreamNegotiationError(
            "Artifact events received from agent whose Agent Card declared "
            "capabilities.streaming=false; reconcile via unary tasks/get."
        )

    if observed_state not in TERMINAL or not status_final:
        # Non-terminal: keep consuming, never close on status alone.
        return False

    if not ctx.is_resubscribe:
        # Live subscription: terminal status is necessary but not sufficient.
        if ctx.artifact_final_marker_seen:
            return True
        # Status arrived but artifact stream has not declared finality yet.
        raise ArtifactStreamNegotiationError(
            "Terminal status observed on live stream before artifact final "
            "marker; refusing teardown to avoid silent tail loss."
        )

    # Resubscribe replay path.
    if ctx.artifact_event_count == 0 and not ctx.replay_complete_marker_seen:
        raise ArtifactStreamNegotiationError(
            "Resubscribe replay returned terminal status with zero artifact "
            "events and no replay-complete marker; artifacts are UNKNOWN, "
            "not empty. Retention likely expired."
        )

    if not ctx.artifact_final_marker_seen and ctx.artifact_event_count > 0:
        raise ArtifactStreamNegotiationError(
            "Replay contained artifact events but no final marker; "
            "replay is truncated."
        )

    return True
