# 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, BaseHttpResponse, 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_event import ReturnChatEvent
from ..types.return_chat_group import ReturnChatGroup
from ..types.return_chat_group_paged_audio_reconstructions import ReturnChatGroupPagedAudioReconstructions
from ..types.return_chat_group_paged_chats import ReturnChatGroupPagedChats
from ..types.return_chat_group_paged_events import ReturnChatGroupPagedEvents
from ..types.return_paged_chat_groups import ReturnPagedChatGroups


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

    def list_chat_groups(
        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,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ReturnChatGroup]:
        """
        Fetches a paginated list of **Chat Groups**.

        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]
            The unique identifier for an EVI configuration.

            Filter Chat Groups to only include Chats that used this `config_id` in their most recent Chat.

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

        Returns
        -------
        SyncPager[ReturnChatGroup]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            "v0/evi/chat_groups",
            method="GET",
            params={
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
                "config_id": config_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnPagedChatGroups,
                    parse_obj_as(
                        type_=ReturnPagedChatGroups,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.chat_groups_page
                _has_next = True
                _get_next = lambda: self.list_chat_groups(
                    page_number=page_number + 1,
                    page_size=page_size,
                    ascending_order=ascending_order,
                    config_id=config_id,
                    request_options=request_options,
                )
                return SyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_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_chat_group(
        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,
    ) -> HttpResponse[ReturnChatGroupPagedChats]:
        """
        Fetches a **ChatGroup** by ID, including a paginated list of **Chats** associated with the **ChatGroup**.

        Parameters
        ----------
        id : str
            Identifier for a Chat Group. 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
        -------
        HttpResponse[ReturnChatGroupPagedChats]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}",
            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:
                _data = typing.cast(
                    ReturnChatGroupPagedChats,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedChats,  # 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)

    def list_chat_group_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]:
        """
        Fetches a paginated list of **Chat** events associated with a **Chat Group**.

        Parameters
        ----------
        id : str
            Identifier for a Chat Group. 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]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}/events",
            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(
                    ReturnChatGroupPagedEvents,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedEvents,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.events_page
                _has_next = True
                _get_next = lambda: self.list_chat_group_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=BaseHttpResponse(response=_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,
        *,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ReturnChatGroupPagedAudioReconstructions]:
        """
        Fetches a paginated list of audio for each **Chat** within the specified **Chat Group**. 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 Group. Formatted as a UUID.

        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.

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

        Returns
        -------
        HttpResponse[ReturnChatGroupPagedAudioReconstructions]
            Success
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}/audio",
            method="GET",
            params={
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReturnChatGroupPagedAudioReconstructions,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedAudioReconstructions,  # 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 AsyncRawChatGroupsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_chat_groups(
        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,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ReturnChatGroup]:
        """
        Fetches a paginated list of **Chat Groups**.

        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]
            The unique identifier for an EVI configuration.

            Filter Chat Groups to only include Chats that used this `config_id` in their most recent Chat.

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

        Returns
        -------
        AsyncPager[ReturnChatGroup]
            Success
        """
        page_number = page_number if page_number is not None else 0

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

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

                return AsyncPager(
                    has_next=_has_next, items=_items, get_next=_get_next, response=BaseHttpResponse(response=_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_chat_group(
        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,
    ) -> AsyncHttpResponse[ReturnChatGroupPagedChats]:
        """
        Fetches a **ChatGroup** by ID, including a paginated list of **Chats** associated with the **ChatGroup**.

        Parameters
        ----------
        id : str
            Identifier for a Chat Group. 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
        -------
        AsyncHttpResponse[ReturnChatGroupPagedChats]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}",
            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:
                _data = typing.cast(
                    ReturnChatGroupPagedChats,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedChats,  # 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)

    async def list_chat_group_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]:
        """
        Fetches a paginated list of **Chat** events associated with a **Chat Group**.

        Parameters
        ----------
        id : str
            Identifier for a Chat Group. 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]
            Success
        """
        page_number = page_number if page_number is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}/events",
            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(
                    ReturnChatGroupPagedEvents,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedEvents,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.events_page
                _has_next = True

                async def _get_next():
                    return await self.list_chat_group_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=BaseHttpResponse(response=_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,
        *,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ReturnChatGroupPagedAudioReconstructions]:
        """
        Fetches a paginated list of audio for each **Chat** within the specified **Chat Group**. 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 Group. Formatted as a UUID.

        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.

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

        Returns
        -------
        AsyncHttpResponse[ReturnChatGroupPagedAudioReconstructions]
            Success
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chat_groups/{jsonable_encoder(id)}/audio",
            method="GET",
            params={
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReturnChatGroupPagedAudioReconstructions,
                    parse_obj_as(
                        type_=ReturnChatGroupPagedAudioReconstructions,  # 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)
