from http import HTTPStatus
from typing import Any
from urllib.parse import quote

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.a2a_task_event import A2ATaskEvent
from ...models.error_response import ErrorResponse
from ...models.http_validation_error import HTTPValidationError
from ...models.send_notification_to_conversation_response_send_notification_to_conversation_api_conversations_conversation_id_notification_post import (
    SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost,
)
from ...models.tool_progress_event import ToolProgressEvent
from ...types import Response


def _get_kwargs(
    conversation_id: str,
    *,
    body: A2ATaskEvent | ToolProgressEvent,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/api/conversations/{conversation_id}/notification".format(
            conversation_id=quote(str(conversation_id), safe=""),
        ),
    }

    if isinstance(body, ToolProgressEvent):
        _kwargs["json"] = body.to_dict()
    else:
        _kwargs["json"] = body.to_dict()

    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> (
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
    | None
):
    if response.status_code == 200:
        response_200 = SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost.from_dict(
            response.json()
        )

        return response_200

    if response.status_code == 404:
        response_404 = ErrorResponse.from_dict(response.json())

        return response_404

    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422

    if response.status_code == 500:
        response_500 = ErrorResponse.from_dict(response.json())

        return response_500

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    body: A2ATaskEvent | ToolProgressEvent,
) -> Response[
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
]:
    """Send Notification To Conversation

     Send a notification event to an active conversation's WebSocket.

    This endpoint allows MCP servers to send real-time progress updates
    to the conversation UI without requiring authentication (used internally).

    Accepts both Pydantic AI tool_progress events and A2A Task notifications,
    and converts A2A Tasks to tool_progress format.
    NOTE: This is temporary, eventually only A2A Task events should be accepted.

    Args:
        event: Event data to send (ToolProgressEvent or A2ATaskEvent)
        conversation_id: The conversation ID

    Returns:
        Success message

    Raises:
        HTTPException: If conversation not found or WebSocket unavailable

    Args:
        conversation_id (str): The ID of the conversation to send notification to
        body (A2ATaskEvent | ToolProgressEvent):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[ErrorResponse | HTTPValidationError | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost]
    """

    kwargs = _get_kwargs(
        conversation_id=conversation_id,
        body=body,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    body: A2ATaskEvent | ToolProgressEvent,
) -> (
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
    | None
):
    """Send Notification To Conversation

     Send a notification event to an active conversation's WebSocket.

    This endpoint allows MCP servers to send real-time progress updates
    to the conversation UI without requiring authentication (used internally).

    Accepts both Pydantic AI tool_progress events and A2A Task notifications,
    and converts A2A Tasks to tool_progress format.
    NOTE: This is temporary, eventually only A2A Task events should be accepted.

    Args:
        event: Event data to send (ToolProgressEvent or A2ATaskEvent)
        conversation_id: The conversation ID

    Returns:
        Success message

    Raises:
        HTTPException: If conversation not found or WebSocket unavailable

    Args:
        conversation_id (str): The ID of the conversation to send notification to
        body (A2ATaskEvent | ToolProgressEvent):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        ErrorResponse | HTTPValidationError | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
    """

    return sync_detailed(
        conversation_id=conversation_id,
        client=client,
        body=body,
    ).parsed


async def asyncio_detailed(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    body: A2ATaskEvent | ToolProgressEvent,
) -> Response[
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
]:
    """Send Notification To Conversation

     Send a notification event to an active conversation's WebSocket.

    This endpoint allows MCP servers to send real-time progress updates
    to the conversation UI without requiring authentication (used internally).

    Accepts both Pydantic AI tool_progress events and A2A Task notifications,
    and converts A2A Tasks to tool_progress format.
    NOTE: This is temporary, eventually only A2A Task events should be accepted.

    Args:
        event: Event data to send (ToolProgressEvent or A2ATaskEvent)
        conversation_id: The conversation ID

    Returns:
        Success message

    Raises:
        HTTPException: If conversation not found or WebSocket unavailable

    Args:
        conversation_id (str): The ID of the conversation to send notification to
        body (A2ATaskEvent | ToolProgressEvent):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[ErrorResponse | HTTPValidationError | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost]
    """

    kwargs = _get_kwargs(
        conversation_id=conversation_id,
        body=body,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    body: A2ATaskEvent | ToolProgressEvent,
) -> (
    ErrorResponse
    | HTTPValidationError
    | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
    | None
):
    """Send Notification To Conversation

     Send a notification event to an active conversation's WebSocket.

    This endpoint allows MCP servers to send real-time progress updates
    to the conversation UI without requiring authentication (used internally).

    Accepts both Pydantic AI tool_progress events and A2A Task notifications,
    and converts A2A Tasks to tool_progress format.
    NOTE: This is temporary, eventually only A2A Task events should be accepted.

    Args:
        event: Event data to send (ToolProgressEvent or A2ATaskEvent)
        conversation_id: The conversation ID

    Returns:
        Success message

    Raises:
        HTTPException: If conversation not found or WebSocket unavailable

    Args:
        conversation_id (str): The ID of the conversation to send notification to
        body (A2ATaskEvent | ToolProgressEvent):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        ErrorResponse | HTTPValidationError | SendNotificationToConversationResponseSendNotificationToConversationApiConversationsConversationIdNotificationPost
    """

    return (
        await asyncio_detailed(
            conversation_id=conversation_id,
            client=client,
            body=body,
        )
    ).parsed
