# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-task-whose-agent-card-capabilities-streaming-flag-disagrees-with-the-transport-actually-negotiated-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-an-a2a-task-whose-agent-card-capabilities-streaming-flag-disagrees-with-the-transport-actually-negotiated-at-the.warrant.json
# Markdown SHA-256:   d9180a9d386cfaed9f8b21e7b89ec7b08e67ab7947c7e8bf00e7bbd7b1b62241
# Code AST SHA-256:   b9a7fb9f5b36a95295544f8f25d40f3a657b017f945e51e170fe0bd30fb0366f
# Verified Classes:   TransportNegotiationError, TaskState, AgentCard, FirstResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import json
from dataclasses import dataclass
from enum import Enum
from typing import Any


class TransportNegotiationError(RuntimeError):
    """Raised when the negotiated transport contradicts the Agent Card's advertised capability."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass(frozen=True)
class AgentCard:
    url: str
    streaming: bool
    push_notifications: bool


@dataclass(frozen=True)
class FirstResponse:
    status_code: int
    content_type: str
    body: dict[str, Any]


def negotiate_subscription(card: AgentCard, response: FirstResponse) -> str:
    """
    Validate that a tasks/sendSubscribe response actually established a stream
    or a pollable task. Returns a handle token on success.

    The Card's streaming flag is a prior, not a commitment. The first response
    is the contract.
    """
    if response.status_code != 200:
        raise TransportNegotiationError(
            f"subscription rejected with status {response.status_code}; "
            f"card advertised streaming={card.streaming}"
        )

    task = response.body.get("task") or response.body
    state = TaskState(task.get("status", {}).get("state", "submitted"))
    task_id = task.get("id")
    if not task_id:
        raise TransportNegotiationError("response contained no task id")

    is_stream = response.content_type.split(";")[0].strip() == "text/event-stream"

    if is_stream:
        # Live stream handle: caller can observe terminal state.
        return f"stream:{task_id}"

    # Non-streaming response. This is only acceptable if the card did NOT
    # advertise streaming, OR the task is already terminal.
    if card.streaming and state not in (TaskState.COMPLETED, TaskState.FAILED):
        raise TransportNegotiationError(
            f"card advertised streaming=true but endpoint returned "
            f"content-type={response.content_type!r} with non-terminal state={state.value!r}; "
            f"task {task_id} is orphaned (no stream, no terminal event)"
        )

    if state in (TaskState.COMPLETED, TaskState.FAILED):
        return f"terminal:{task_id}"

    # Non-streaming, non-terminal: caller MUST be able to poll.
    # We cannot verify pollability here; return a poll handle that the
    # caller must confirm with tasks/get before committing.
    return f"poll-unverified:{task_id}"


def create_task(card: AgentCard, response: FirstResponse) -> str:
    try:
        return negotiate_subscription(card, response)
    except TransportNegotiationError:
        # Do NOT retry with a new idempotency key: that orphans a task on the peer.
        # Re-route to a transport consistent with the observed response, or abort.
        raise


# Example trigger: card says streaming, endpoint returns JSON ack for a non-terminal task.
card = AgentCard(url="https://peer.example/a2a", streaming=True, push_notifications=False)
bad_response = FirstResponse(
    status_code=200,
    content_type="application/json",
    body={"id": "task-8f2c", "status": {"state": "submitted"}, "kind": "task"},
)
create_task(card, bad_response)  # raises TransportNegotiationError
