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.activity_delta_event import ActivityDeltaEvent
from ...models.activity_message import ActivityMessage
from ...models.activity_snapshot_event import ActivitySnapshotEvent
from ...models.assistant_message import AssistantMessage
from ...models.custom_event import CustomEvent
from ...models.developer_message import DeveloperMessage
from ...models.error_response import ErrorResponse
from ...models.http_validation_error import HTTPValidationError
from ...models.messages_snapshot_event import MessagesSnapshotEvent
from ...models.raw_event import RawEvent
from ...models.run_error_event import RunErrorEvent
from ...models.run_finished_event import RunFinishedEvent
from ...models.run_started_event import RunStartedEvent
from ...models.state_delta_event import StateDeltaEvent
from ...models.state_snapshot_event import StateSnapshotEvent
from ...models.step_finished_event import StepFinishedEvent
from ...models.step_started_event import StepStartedEvent
from ...models.system_message import SystemMessage
from ...models.text_message_chunk_event import TextMessageChunkEvent
from ...models.text_message_content_event import TextMessageContentEvent
from ...models.text_message_end_event import TextMessageEndEvent
from ...models.text_message_start_event import TextMessageStartEvent
from ...models.tool_call_args_event import ToolCallArgsEvent
from ...models.tool_call_chunk_event import ToolCallChunkEvent
from ...models.tool_call_end_event import ToolCallEndEvent
from ...models.tool_call_result_event import ToolCallResultEvent
from ...models.tool_call_start_event import ToolCallStartEvent
from ...models.tool_message import ToolMessage
from ...models.user_message import UserMessage
from ...types import UNSET, Response, Unset


def _get_kwargs(
    conversation_id: str,
    *,
    limit: int | Unset = 10000000,
    offset: int | Unset = 0,
) -> dict[str, Any]:
    params: dict[str, Any] = {}

    params["limit"] = limit

    params["offset"] = offset

    params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

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

    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> (
    ErrorResponse
    | HTTPValidationError
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
    | None
):
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:

            def _parse_response_200_item(
                data: object,
            ) -> (
                ActivityDeltaEvent
                | ActivityMessage
                | ActivitySnapshotEvent
                | AssistantMessage
                | CustomEvent
                | DeveloperMessage
                | MessagesSnapshotEvent
                | RawEvent
                | RunErrorEvent
                | RunFinishedEvent
                | RunStartedEvent
                | StateDeltaEvent
                | StateSnapshotEvent
                | StepFinishedEvent
                | StepStartedEvent
                | SystemMessage
                | TextMessageChunkEvent
                | TextMessageContentEvent
                | TextMessageEndEvent
                | TextMessageStartEvent
                | ToolCallArgsEvent
                | ToolCallChunkEvent
                | ToolCallEndEvent
                | ToolCallResultEvent
                | ToolCallStartEvent
                | ToolMessage
                | UserMessage
            ):
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_0 = TextMessageStartEvent.from_dict(data)

                    return response_200_item_type_0_type_0
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_1 = TextMessageContentEvent.from_dict(data)

                    return response_200_item_type_0_type_1
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_2 = TextMessageEndEvent.from_dict(data)

                    return response_200_item_type_0_type_2
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_3 = TextMessageChunkEvent.from_dict(data)

                    return response_200_item_type_0_type_3
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_4 = ToolCallStartEvent.from_dict(data)

                    return response_200_item_type_0_type_4
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_5 = ToolCallArgsEvent.from_dict(data)

                    return response_200_item_type_0_type_5
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_6 = ToolCallEndEvent.from_dict(data)

                    return response_200_item_type_0_type_6
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_7 = ToolCallChunkEvent.from_dict(data)

                    return response_200_item_type_0_type_7
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_8 = ToolCallResultEvent.from_dict(data)

                    return response_200_item_type_0_type_8
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_9 = StateSnapshotEvent.from_dict(data)

                    return response_200_item_type_0_type_9
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_10 = StateDeltaEvent.from_dict(data)

                    return response_200_item_type_0_type_10
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_11 = MessagesSnapshotEvent.from_dict(data)

                    return response_200_item_type_0_type_11
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_12 = ActivitySnapshotEvent.from_dict(data)

                    return response_200_item_type_0_type_12
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_13 = ActivityDeltaEvent.from_dict(data)

                    return response_200_item_type_0_type_13
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_14 = RawEvent.from_dict(data)

                    return response_200_item_type_0_type_14
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_15 = CustomEvent.from_dict(data)

                    return response_200_item_type_0_type_15
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_16 = RunStartedEvent.from_dict(data)

                    return response_200_item_type_0_type_16
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_17 = RunFinishedEvent.from_dict(data)

                    return response_200_item_type_0_type_17
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_18 = RunErrorEvent.from_dict(data)

                    return response_200_item_type_0_type_18
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_19 = StepStartedEvent.from_dict(data)

                    return response_200_item_type_0_type_19
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_0_type_20 = StepFinishedEvent.from_dict(data)

                    return response_200_item_type_0_type_20
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_1_type_0 = DeveloperMessage.from_dict(data)

                    return response_200_item_type_1_type_0
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_1_type_1 = SystemMessage.from_dict(data)

                    return response_200_item_type_1_type_1
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_1_type_2 = AssistantMessage.from_dict(data)

                    return response_200_item_type_1_type_2
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_1_type_3 = UserMessage.from_dict(data)

                    return response_200_item_type_1_type_3
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                try:
                    if not isinstance(data, dict):
                        raise TypeError()
                    response_200_item_type_1_type_4 = ToolMessage.from_dict(data)

                    return response_200_item_type_1_type_4
                except (TypeError, ValueError, AttributeError, KeyError):
                    pass
                if not isinstance(data, dict):
                    raise TypeError()
                response_200_item_type_1_type_5 = ActivityMessage.from_dict(data)

                return response_200_item_type_1_type_5

            response_200_item = _parse_response_200_item(response_200_item_data)

            response_200.append(response_200_item)

        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 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
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
]:
    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,
    limit: int | Unset = 10000000,
    offset: int | Unset = 0,
) -> Response[
    ErrorResponse
    | HTTPValidationError
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
]:
    """Get Conversation Messages

     Get messages for a conversation as AG-UI events (simple & direct).

    This endpoint retrieves AG-UI events directly from storage - no conversion needed!

    Args:
        conversation_id: The ID of the conversation to get messages for

    Returns:
        List of AG-UI events

    Args:
        conversation_id (str): The ID of the conversation to get messages for
        limit (int | Unset):  Default: 10000000.
        offset (int | Unset):  Default: 0.

    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 | list[ActivityDeltaEvent | ActivityMessage | ActivitySnapshotEvent | AssistantMessage | CustomEvent | DeveloperMessage | MessagesSnapshotEvent | RawEvent | RunErrorEvent | RunFinishedEvent | RunStartedEvent | StateDeltaEvent | StateSnapshotEvent | StepFinishedEvent | StepStartedEvent | SystemMessage | TextMessageChunkEvent | TextMessageContentEvent | TextMessageEndEvent | TextMessageStartEvent | ToolCallArgsEvent | ToolCallChunkEvent | ToolCallEndEvent | ToolCallResultEvent | ToolCallStartEvent | ToolMessage | UserMessage]]
    """

    kwargs = _get_kwargs(
        conversation_id=conversation_id,
        limit=limit,
        offset=offset,
    )

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

    return _build_response(client=client, response=response)


def sync(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    limit: int | Unset = 10000000,
    offset: int | Unset = 0,
) -> (
    ErrorResponse
    | HTTPValidationError
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
    | None
):
    """Get Conversation Messages

     Get messages for a conversation as AG-UI events (simple & direct).

    This endpoint retrieves AG-UI events directly from storage - no conversion needed!

    Args:
        conversation_id: The ID of the conversation to get messages for

    Returns:
        List of AG-UI events

    Args:
        conversation_id (str): The ID of the conversation to get messages for
        limit (int | Unset):  Default: 10000000.
        offset (int | Unset):  Default: 0.

    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 | list[ActivityDeltaEvent | ActivityMessage | ActivitySnapshotEvent | AssistantMessage | CustomEvent | DeveloperMessage | MessagesSnapshotEvent | RawEvent | RunErrorEvent | RunFinishedEvent | RunStartedEvent | StateDeltaEvent | StateSnapshotEvent | StepFinishedEvent | StepStartedEvent | SystemMessage | TextMessageChunkEvent | TextMessageContentEvent | TextMessageEndEvent | TextMessageStartEvent | ToolCallArgsEvent | ToolCallChunkEvent | ToolCallEndEvent | ToolCallResultEvent | ToolCallStartEvent | ToolMessage | UserMessage]
    """

    return sync_detailed(
        conversation_id=conversation_id,
        client=client,
        limit=limit,
        offset=offset,
    ).parsed


async def asyncio_detailed(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    limit: int | Unset = 10000000,
    offset: int | Unset = 0,
) -> Response[
    ErrorResponse
    | HTTPValidationError
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
]:
    """Get Conversation Messages

     Get messages for a conversation as AG-UI events (simple & direct).

    This endpoint retrieves AG-UI events directly from storage - no conversion needed!

    Args:
        conversation_id: The ID of the conversation to get messages for

    Returns:
        List of AG-UI events

    Args:
        conversation_id (str): The ID of the conversation to get messages for
        limit (int | Unset):  Default: 10000000.
        offset (int | Unset):  Default: 0.

    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 | list[ActivityDeltaEvent | ActivityMessage | ActivitySnapshotEvent | AssistantMessage | CustomEvent | DeveloperMessage | MessagesSnapshotEvent | RawEvent | RunErrorEvent | RunFinishedEvent | RunStartedEvent | StateDeltaEvent | StateSnapshotEvent | StepFinishedEvent | StepStartedEvent | SystemMessage | TextMessageChunkEvent | TextMessageContentEvent | TextMessageEndEvent | TextMessageStartEvent | ToolCallArgsEvent | ToolCallChunkEvent | ToolCallEndEvent | ToolCallResultEvent | ToolCallStartEvent | ToolMessage | UserMessage]]
    """

    kwargs = _get_kwargs(
        conversation_id=conversation_id,
        limit=limit,
        offset=offset,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    conversation_id: str,
    *,
    client: AuthenticatedClient,
    limit: int | Unset = 10000000,
    offset: int | Unset = 0,
) -> (
    ErrorResponse
    | HTTPValidationError
    | list[
        ActivityDeltaEvent
        | ActivityMessage
        | ActivitySnapshotEvent
        | AssistantMessage
        | CustomEvent
        | DeveloperMessage
        | MessagesSnapshotEvent
        | RawEvent
        | RunErrorEvent
        | RunFinishedEvent
        | RunStartedEvent
        | StateDeltaEvent
        | StateSnapshotEvent
        | StepFinishedEvent
        | StepStartedEvent
        | SystemMessage
        | TextMessageChunkEvent
        | TextMessageContentEvent
        | TextMessageEndEvent
        | TextMessageStartEvent
        | ToolCallArgsEvent
        | ToolCallChunkEvent
        | ToolCallEndEvent
        | ToolCallResultEvent
        | ToolCallStartEvent
        | ToolMessage
        | UserMessage
    ]
    | None
):
    """Get Conversation Messages

     Get messages for a conversation as AG-UI events (simple & direct).

    This endpoint retrieves AG-UI events directly from storage - no conversion needed!

    Args:
        conversation_id: The ID of the conversation to get messages for

    Returns:
        List of AG-UI events

    Args:
        conversation_id (str): The ID of the conversation to get messages for
        limit (int | Unset):  Default: 10000000.
        offset (int | Unset):  Default: 0.

    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 | list[ActivityDeltaEvent | ActivityMessage | ActivitySnapshotEvent | AssistantMessage | CustomEvent | DeveloperMessage | MessagesSnapshotEvent | RawEvent | RunErrorEvent | RunFinishedEvent | RunStartedEvent | StateDeltaEvent | StateSnapshotEvent | StepFinishedEvent | StepStartedEvent | SystemMessage | TextMessageChunkEvent | TextMessageContentEvent | TextMessageEndEvent | TextMessageStartEvent | ToolCallArgsEvent | ToolCallChunkEvent | ToolCallEndEvent | ToolCallResultEvent | ToolCallStartEvent | ToolMessage | UserMessage]
    """

    return (
        await asyncio_detailed(
            conversation_id=conversation_id,
            client=client,
            limit=limit,
            offset=offset,
        )
    ).parsed
