# 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.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.paginated_messages_response import PaginatedMessagesResponse
from ..types.task_message import TaskMessage
from ..types.task_message_content import TaskMessageContent
from .types.create_task_message_request_streaming_status import CreateTaskMessageRequestStreamingStatus
from .types.messages_list_paginated_request_direction import MessagesListPaginatedRequestDirection
from .types.update_task_message_request_streaming_status import UpdateTaskMessageRequestStreamingStatus

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


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

    def list(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        order_by: typing.Optional[str] = None,
        order_direction: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[TaskMessage]]:
        """
        List messages for a task with offset-based pagination.

        For cursor-based pagination with infinite scroll support, use /messages/paginated.

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

        limit : typing.Optional[int]

        page_number : typing.Optional[int]

        order_by : typing.Optional[str]

        order_direction : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[typing.List[TaskMessage]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "messages",
            method="GET",
            params={
                "limit": limit,
                "page_number": page_number,
                "order_by": order_by,
                "order_direction": order_direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[TaskMessage],
                    parse_obj_as(
                        type_=typing.List[TaskMessage],  # 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)

    def create(
        self,
        *,
        content: TaskMessageContent,
        task_id: str,
        streaming_status: typing.Optional[CreateTaskMessageRequestStreamingStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TaskMessage]:
        """
        Parameters
        ----------
        content : TaskMessageContent

        task_id : str

        streaming_status : typing.Optional[CreateTaskMessageRequestStreamingStatus]

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

        Returns
        -------
        HttpResponse[TaskMessage]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "messages",
            method="POST",
            json={
                "content": convert_and_respect_annotation_metadata(
                    object_=content, annotation=TaskMessageContent, direction="write"
                ),
                "streaming_status": streaming_status,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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)

    def list_paginated(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        direction: typing.Optional[MessagesListPaginatedRequestDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PaginatedMessagesResponse]:
        """
        List messages for a task with cursor-based pagination.

        This endpoint is designed for infinite scroll UIs where new messages may arrive
        while paginating through older ones.

        Args:
            task_id: The task ID to filter messages by
            limit: Maximum number of messages to return (default: 50)
            cursor: Opaque cursor string for pagination. Pass the `next_cursor` from
                    a previous response to get the next page.
            direction: Pagination direction - "older" to get older messages (default),
                       "newer" to get newer messages.

        Returns:
            PaginatedMessagesResponse with:
            - data: List of messages (newest first when direction="older")
            - next_cursor: Cursor for fetching the next page (null if no more pages)
            - has_more: Whether there are more messages to fetch

        Example:
            First request: GET /messages/paginated?task_id=xxx&limit=50
            Next page: GET /messages/paginated?task_id=xxx&limit=50&cursor=<next_cursor>

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

        limit : typing.Optional[int]

        cursor : typing.Optional[str]

        direction : typing.Optional[MessagesListPaginatedRequestDirection]

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

        Returns
        -------
        HttpResponse[PaginatedMessagesResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "messages/paginated",
            method="GET",
            params={
                "limit": limit,
                "cursor": cursor,
                "direction": direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PaginatedMessagesResponse,
                    parse_obj_as(
                        type_=PaginatedMessagesResponse,  # 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)

    def retrieve(
        self, message_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[TaskMessage]:
        """
        Get a message by ID. Authorization is derived from the message's parent task.

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

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

        Returns
        -------
        HttpResponse[TaskMessage]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"messages/{jsonable_encoder(message_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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)

    def update(
        self,
        message_id: str,
        *,
        content: TaskMessageContent,
        task_id: str,
        streaming_status: typing.Optional[UpdateTaskMessageRequestStreamingStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TaskMessage]:
        """
        Parameters
        ----------
        message_id : str

        content : TaskMessageContent

        task_id : str

        streaming_status : typing.Optional[UpdateTaskMessageRequestStreamingStatus]

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

        Returns
        -------
        HttpResponse[TaskMessage]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"messages/{jsonable_encoder(message_id)}",
            method="PUT",
            json={
                "content": convert_and_respect_annotation_metadata(
                    object_=content, annotation=TaskMessageContent, direction="write"
                ),
                "streaming_status": streaming_status,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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 AsyncRawMessagesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        order_by: typing.Optional[str] = None,
        order_direction: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[TaskMessage]]:
        """
        List messages for a task with offset-based pagination.

        For cursor-based pagination with infinite scroll support, use /messages/paginated.

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

        limit : typing.Optional[int]

        page_number : typing.Optional[int]

        order_by : typing.Optional[str]

        order_direction : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[TaskMessage]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "messages",
            method="GET",
            params={
                "limit": limit,
                "page_number": page_number,
                "order_by": order_by,
                "order_direction": order_direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[TaskMessage],
                    parse_obj_as(
                        type_=typing.List[TaskMessage],  # 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)

    async def create(
        self,
        *,
        content: TaskMessageContent,
        task_id: str,
        streaming_status: typing.Optional[CreateTaskMessageRequestStreamingStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TaskMessage]:
        """
        Parameters
        ----------
        content : TaskMessageContent

        task_id : str

        streaming_status : typing.Optional[CreateTaskMessageRequestStreamingStatus]

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

        Returns
        -------
        AsyncHttpResponse[TaskMessage]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "messages",
            method="POST",
            json={
                "content": convert_and_respect_annotation_metadata(
                    object_=content, annotation=TaskMessageContent, direction="write"
                ),
                "streaming_status": streaming_status,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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)

    async def list_paginated(
        self,
        *,
        task_id: str,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        direction: typing.Optional[MessagesListPaginatedRequestDirection] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PaginatedMessagesResponse]:
        """
        List messages for a task with cursor-based pagination.

        This endpoint is designed for infinite scroll UIs where new messages may arrive
        while paginating through older ones.

        Args:
            task_id: The task ID to filter messages by
            limit: Maximum number of messages to return (default: 50)
            cursor: Opaque cursor string for pagination. Pass the `next_cursor` from
                    a previous response to get the next page.
            direction: Pagination direction - "older" to get older messages (default),
                       "newer" to get newer messages.

        Returns:
            PaginatedMessagesResponse with:
            - data: List of messages (newest first when direction="older")
            - next_cursor: Cursor for fetching the next page (null if no more pages)
            - has_more: Whether there are more messages to fetch

        Example:
            First request: GET /messages/paginated?task_id=xxx&limit=50
            Next page: GET /messages/paginated?task_id=xxx&limit=50&cursor=<next_cursor>

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

        limit : typing.Optional[int]

        cursor : typing.Optional[str]

        direction : typing.Optional[MessagesListPaginatedRequestDirection]

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

        Returns
        -------
        AsyncHttpResponse[PaginatedMessagesResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "messages/paginated",
            method="GET",
            params={
                "limit": limit,
                "cursor": cursor,
                "direction": direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PaginatedMessagesResponse,
                    parse_obj_as(
                        type_=PaginatedMessagesResponse,  # 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)

    async def retrieve(
        self, message_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[TaskMessage]:
        """
        Get a message by ID. Authorization is derived from the message's parent task.

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

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

        Returns
        -------
        AsyncHttpResponse[TaskMessage]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"messages/{jsonable_encoder(message_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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)

    async def update(
        self,
        message_id: str,
        *,
        content: TaskMessageContent,
        task_id: str,
        streaming_status: typing.Optional[UpdateTaskMessageRequestStreamingStatus] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TaskMessage]:
        """
        Parameters
        ----------
        message_id : str

        content : TaskMessageContent

        task_id : str

        streaming_status : typing.Optional[UpdateTaskMessageRequestStreamingStatus]

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

        Returns
        -------
        AsyncHttpResponse[TaskMessage]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"messages/{jsonable_encoder(message_id)}",
            method="PUT",
            json={
                "content": convert_and_respect_annotation_metadata(
                    object_=content, annotation=TaskMessageContent, direction="write"
                ),
                "streaming_status": streaming_status,
                "task_id": task_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TaskMessage,
                    parse_obj_as(
                        type_=TaskMessage,  # 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)
