# 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.bad_request_error import BadRequestError
from ..types.error_response import ErrorResponse
from ..types.return_chat import ReturnChat
from ..types.return_chat_audio_reconstruction import ReturnChatAudioReconstruction
from ..types.return_chat_event import ReturnChatEvent
from ..types.return_chat_paged_events import ReturnChatPagedEvents
from ..types.return_paged_chats import ReturnPagedChats


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

    def list_chats(
        self,
        *,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        config_id: typing.Optional[str] = None,
        status: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ReturnChat, ReturnPagedChats]:
        """
        Fetches a paginated list of **Chats**.

        Parameters
        ----------
        page_number : typing.Optional[int]
            Specifies the page number to retrieve, enabling pagination.

            This parameter uses zero-based indexing. For example, setting `page_number` to 0 retrieves the first page of results (items 0-9 if `page_size` is 10), setting `page_number` to 1 retrieves the second page (items 10-19), and so on. Defaults to 0, which retrieves the first page.

        page_size : typing.Optional[int]
            Specifies the maximum number of results to include per page, enabling pagination. The value must be between 1 and 100, inclusive.

            For example, if `page_size` is set to 10, each page will include up to 10 items. Defaults to 10.

        ascending_order : typing.Optional[bool]
            Specifies the sorting order of the results based on their creation date. Set to true for ascending order (chronological, with the oldest records first) and false for descending order (reverse-chronological, with the newest records first). Defaults to true.

        config_id : typing.Optional[str]
            Filter to only include chats that used this config.

        status : typing.Optional[str]
            Chat status to apply to the chat. String from the ChatStatus enum.

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

        Returns
        -------
        SyncPager[ReturnChat, ReturnPagedChats]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            "v0/evi/chats",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            params={
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
                "config_id": config_id,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnPagedChats,
                    parse_obj_as(
                        type_=ReturnPagedChats,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.chats_page
                _has_next = True
                _get_next = lambda: self.list_chats(
                    page_number=page_number + 1,
                    page_size=page_size,
                    ascending_order=ascending_order,
                    config_id=config_id,
                    status=status,
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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_chat_events(
        self,
        id: str,
        *,
        page_size: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ReturnChatEvent, ReturnChatPagedEvents]:
        """
        Fetches a paginated list of **Chat** events.

        Parameters
        ----------
        id : str
            Identifier for a Chat. Formatted as a UUID.

        page_size : typing.Optional[int]
            Specifies the maximum number of results to include per page, enabling pagination. The value must be between 1 and 100, inclusive.

            For example, if `page_size` is set to 10, each page will include up to 10 items. Defaults to 10.

        page_number : typing.Optional[int]
            Specifies the page number to retrieve, enabling pagination.

            This parameter uses zero-based indexing. For example, setting `page_number` to 0 retrieves the first page of results (items 0-9 if `page_size` is 10), setting `page_number` to 1 retrieves the second page (items 10-19), and so on. Defaults to 0, which retrieves the first page.

        ascending_order : typing.Optional[bool]
            Specifies the sorting order of the results based on their creation date. Set to true for ascending order (chronological, with the oldest records first) and false for descending order (reverse-chronological, with the newest records first). Defaults to true.

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

        Returns
        -------
        SyncPager[ReturnChatEvent, ReturnChatPagedEvents]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chats/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            params={
                "page_size": page_size,
                "page_number": page_number,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnChatPagedEvents,
                    parse_obj_as(
                        type_=ReturnChatPagedEvents,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.events_page
                _has_next = True
                _get_next = lambda: self.list_chat_events(
                    id,
                    page_size=page_size,
                    page_number=page_number + 1,
                    ascending_order=ascending_order,
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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 get_audio(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ReturnChatAudioReconstruction]:
        """
        Fetches the audio of a previous **Chat**. For more details, see our guide on audio reconstruction [here](/docs/speech-to-speech-evi/faq#can-i-access-the-audio-of-previous-conversations-with-evi).

        Parameters
        ----------
        id : str
            Identifier for a Chat. Formatted as a UUID.

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

        Returns
        -------
        HttpResponse[ReturnChatAudioReconstruction]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chats/{jsonable_encoder(id)}/audio",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReturnChatAudioReconstruction,
                    parse_obj_as(
                        type_=ReturnChatAudioReconstruction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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 AsyncRawChatsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_chats(
        self,
        *,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        config_id: typing.Optional[str] = None,
        status: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ReturnChat, ReturnPagedChats]:
        """
        Fetches a paginated list of **Chats**.

        Parameters
        ----------
        page_number : typing.Optional[int]
            Specifies the page number to retrieve, enabling pagination.

            This parameter uses zero-based indexing. For example, setting `page_number` to 0 retrieves the first page of results (items 0-9 if `page_size` is 10), setting `page_number` to 1 retrieves the second page (items 10-19), and so on. Defaults to 0, which retrieves the first page.

        page_size : typing.Optional[int]
            Specifies the maximum number of results to include per page, enabling pagination. The value must be between 1 and 100, inclusive.

            For example, if `page_size` is set to 10, each page will include up to 10 items. Defaults to 10.

        ascending_order : typing.Optional[bool]
            Specifies the sorting order of the results based on their creation date. Set to true for ascending order (chronological, with the oldest records first) and false for descending order (reverse-chronological, with the newest records first). Defaults to true.

        config_id : typing.Optional[str]
            Filter to only include chats that used this config.

        status : typing.Optional[str]
            Chat status to apply to the chat. String from the ChatStatus enum.

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

        Returns
        -------
        AsyncPager[ReturnChat, ReturnPagedChats]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            "v0/evi/chats",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            params={
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
                "config_id": config_id,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnPagedChats,
                    parse_obj_as(
                        type_=ReturnPagedChats,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.chats_page
                _has_next = True

                async def _get_next():
                    return await self.list_chats(
                        page_number=page_number + 1,
                        page_size=page_size,
                        ascending_order=ascending_order,
                        config_id=config_id,
                        status=status,
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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_chat_events(
        self,
        id: str,
        *,
        page_size: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ReturnChatEvent, ReturnChatPagedEvents]:
        """
        Fetches a paginated list of **Chat** events.

        Parameters
        ----------
        id : str
            Identifier for a Chat. Formatted as a UUID.

        page_size : typing.Optional[int]
            Specifies the maximum number of results to include per page, enabling pagination. The value must be between 1 and 100, inclusive.

            For example, if `page_size` is set to 10, each page will include up to 10 items. Defaults to 10.

        page_number : typing.Optional[int]
            Specifies the page number to retrieve, enabling pagination.

            This parameter uses zero-based indexing. For example, setting `page_number` to 0 retrieves the first page of results (items 0-9 if `page_size` is 10), setting `page_number` to 1 retrieves the second page (items 10-19), and so on. Defaults to 0, which retrieves the first page.

        ascending_order : typing.Optional[bool]
            Specifies the sorting order of the results based on their creation date. Set to true for ascending order (chronological, with the oldest records first) and false for descending order (reverse-chronological, with the newest records first). Defaults to true.

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

        Returns
        -------
        AsyncPager[ReturnChatEvent, ReturnChatPagedEvents]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chats/{jsonable_encoder(id)}",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            params={
                "page_size": page_size,
                "page_number": page_number,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnChatPagedEvents,
                    parse_obj_as(
                        type_=ReturnChatPagedEvents,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.events_page
                _has_next = True

                async def _get_next():
                    return await self.list_chat_events(
                        id,
                        page_size=page_size,
                        page_number=page_number + 1,
                        ascending_order=ascending_order,
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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 get_audio(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ReturnChatAudioReconstruction]:
        """
        Fetches the audio of a previous **Chat**. For more details, see our guide on audio reconstruction [here](/docs/speech-to-speech-evi/faq#can-i-access-the-audio-of-previous-conversations-with-evi).

        Parameters
        ----------
        id : str
            Identifier for a Chat. Formatted as a UUID.

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

        Returns
        -------
        AsyncHttpResponse[ReturnChatAudioReconstruction]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chats/{jsonable_encoder(id)}/audio",
            base_url=self._client_wrapper.get_environment().base,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReturnChatAudioReconstruction,
                    parse_obj_as(
                        type_=ReturnChatAudioReconstruction,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # 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)
