# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pagination import AsyncPager, SyncPager
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.list_messages_v2response import ListMessagesV2Response
from ..types.ui_message import UiMessage
from .types.messages_v2list_request_direction import MessagesV2ListRequestDirection


class RawMessagesV2Client:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        direction: typing.Optional[MessagesV2ListRequestDirection] = None,
        parent_tool_use_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[UiMessage, ListMessagesV2Response]:
        """
        List messages for a task in Vercel AI SDK UIMessage format.

            This endpoint returns messages transformed from raw SDK events into
            a normalized UIMessage format suitable for frontend consumption.

            Features:
            - Tool merging: tool_use and tool_result are combined into single tool parts
            - Complete-units pagination: Never splits tool request/result pairs across pages
            - Runtime transformation: Raw SDK messages are transformed on-demand

            Args:
                task_id: The task ID to filter messages by
                limit: Maximum number of complete messages to return (default: 50)
                cursor: Opaque cursor string for pagination
                direction: Pagination direction - "older" (default) or "newer"
                parent_tool_use_id: Filter messages by parent tool use ID (for subagent context)

            Returns:
                ListMessagesV2Response with UIMessages and pagination info

        Parameters
        ----------
        task_id : str
            The task ID

        limit : typing.Optional[int]

        cursor : typing.Optional[str]

        direction : typing.Optional[MessagesV2ListRequestDirection]

        parent_tool_use_id : typing.Optional[str]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        SyncPager[UiMessage, ListMessagesV2Response]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/messages",
            method="GET",
            params={
                "limit": limit,
                "cursor": cursor,
                "direction": direction,
                "parent_tool_use_id": parent_tool_use_id,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListMessagesV2Response,
                    parse_obj_as(
                        type_=ListMessagesV2Response,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _parsed_next = _parsed_response.next_cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    task_id=task_id,
                    limit=limit,
                    cursor=_parsed_next,
                    direction=direction,
                    parent_tool_use_id=parent_tool_use_id,
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def retrieve(
        self, message_id: str, *, task_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Optional[UiMessage]]:
        """
        Get a single message by ID in UIMessage format.

            Returns the transformed UIMessage or null if not found.

        Parameters
        ----------
        message_id : str

        task_id : str
            The task ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Optional[UiMessage]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/messages/{jsonable_encoder(message_id)}",
            method="GET",
            params={
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[UiMessage],
                    parse_obj_as(
                        type_=typing.Optional[UiMessage],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawMessagesV2Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        direction: typing.Optional[MessagesV2ListRequestDirection] = None,
        parent_tool_use_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[UiMessage, ListMessagesV2Response]:
        """
        List messages for a task in Vercel AI SDK UIMessage format.

            This endpoint returns messages transformed from raw SDK events into
            a normalized UIMessage format suitable for frontend consumption.

            Features:
            - Tool merging: tool_use and tool_result are combined into single tool parts
            - Complete-units pagination: Never splits tool request/result pairs across pages
            - Runtime transformation: Raw SDK messages are transformed on-demand

            Args:
                task_id: The task ID to filter messages by
                limit: Maximum number of complete messages to return (default: 50)
                cursor: Opaque cursor string for pagination
                direction: Pagination direction - "older" (default) or "newer"
                parent_tool_use_id: Filter messages by parent tool use ID (for subagent context)

            Returns:
                ListMessagesV2Response with UIMessages and pagination info

        Parameters
        ----------
        task_id : str
            The task ID

        limit : typing.Optional[int]

        cursor : typing.Optional[str]

        direction : typing.Optional[MessagesV2ListRequestDirection]

        parent_tool_use_id : typing.Optional[str]

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncPager[UiMessage, ListMessagesV2Response]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/messages",
            method="GET",
            params={
                "limit": limit,
                "cursor": cursor,
                "direction": direction,
                "parent_tool_use_id": parent_tool_use_id,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListMessagesV2Response,
                    parse_obj_as(
                        type_=ListMessagesV2Response,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _parsed_next = _parsed_response.next_cursor
                _has_next = _parsed_next is not None and _parsed_next != ""

                async def _get_next():
                    return await self.list(
                        task_id=task_id,
                        limit=limit,
                        cursor=_parsed_next,
                        direction=direction,
                        parent_tool_use_id=parent_tool_use_id,
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def retrieve(
        self, message_id: str, *, task_id: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Optional[UiMessage]]:
        """
        Get a single message by ID in UIMessage format.

            Returns the transformed UIMessage or null if not found.

        Parameters
        ----------
        message_id : str

        task_id : str
            The task ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Optional[UiMessage]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/messages/{jsonable_encoder(message_id)}",
            method="GET",
            params={
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[UiMessage],
                    parse_obj_as(
                        type_=typing.Optional[UiMessage],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
