# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-stale-rather-than-authoritative-during-cross-vendor-task-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-stale-rather-than-authoritative-during-cross-vendor-task-negotiation.warrant.json
# Markdown SHA-256:   49791fa2e5c454e92311e996f1eb733e4a722c4ea5ac7c861cac06b7e94336b4
# Code AST SHA-256:   b063b40320a8bfd229ed077e1292f7216e2c9955b03dc4690fca1975fd60355d
# Verified Classes:   LifecycleAuthorityError, TaskOutcome, AgentCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class LifecycleAuthorityError(RuntimeError):
    """Raised when an Agent Card is used to authorize a lifecycle decision
    it cannot actually guarantee (e.g., stream closure implies resubscribable)."""


class TaskOutcome(Enum):
    COMPLETED = "completed"
    FAILED_UNKNOWN = "failed_unknown"
    PENDING = "pending"


@dataclass(frozen=True)
class AgentCard:
    streaming: bool
    card_version: str | None
    skills: tuple[str, ...]


def resolve_stream_close(
    card: AgentCard,
    *,
    saw_final_event: bool,
    resubscribe_supported_by_probe: bool,
    tasks_get_returns_not_found: bool,
) -> TaskOutcome:
    """Decide the true outcome of a task whose SSE stream closed cleanly.

    The card may route us to streaming, but it may NOT authorize the claim
    that a closed stream means a resubscribable, still-live task.
    """
    if saw_final_event:
        return TaskOutcome.COMPLETED

    # A clean FIN with no terminal event is NOT a terminal state.
    if not card.streaming:
        # Non-streaming peers must have delivered a terminal poll result.
        raise LifecycleAuthorityError(
            "stream closed on non-streaming peer without terminal event; "
            "card cannot authorize a pending interpretation"
        )

    if not resubscribe_supported_by_probe:
        # Card said streaming=true, but lifecycle support was never probed.
        # Demote to failed-unknown rather than trusting the card.
        if tasks_get_returns_not_found:
            return TaskOutcome.FAILED_UNKNOWN
        return TaskOutcome.PENDING

    if tasks_get_returns_not_found:
        # Peer GC'd the task without emitting a terminal event.
        raise LifecycleAuthorityError(
            f"peer {card.card_version!r} advertised streaming but dropped task "
            "without terminal-state emission; treat as failed-unknown, not pending"
        )

    return TaskOutcome.PENDING
