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

import typing
from ...core.client_wrapper import SyncClientWrapper
from ..types.voice_provider import VoiceProvider
from ...core.request_options import RequestOptions
from ...core.pagination import SyncPager
from ..types.return_voice import ReturnVoice
from ..types.return_paged_voices import ReturnPagedVoices
from ...core.pydantic_utilities import parse_obj_as
from ..errors.bad_request_error import BadRequestError
from ..types.error_response import ErrorResponse
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ...core.client_wrapper import AsyncClientWrapper
from ...core.pagination import AsyncPager

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


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

    def list(
        self,
        *,
        provider: VoiceProvider,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[ReturnVoice]:
        """
        Lists voices in your **Voice Library**. Set provider to `HUME_AI` to list Hume's preset voices, or to `CUSTOM_VOICE` to a custom voice created in your account.

        Parameters
        ----------
        provider : VoiceProvider
            Specifies whether to return custom voices created in your account or shared voices provided by Hume

        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]

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

        Returns
        -------
        SyncPager[ReturnVoice]
            Success

        Examples
        --------
        from hume import HumeClient

        client = HumeClient(
            api_key="YOUR_API_KEY",
        )
        response = client.tts.voices.list(
            provider="CUSTOM_VOICE",
        )
        for item in response:
            yield item
        # alternatively, you can paginate page-by-page
        for page in response.iter_pages():
            yield page
        """
        page_number = page_number if page_number is not None else 1
        _response = self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="GET",
            params={
                "provider": provider,
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnPagedVoices,
                    parse_obj_as(
                        type_=ReturnPagedVoices,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = True
                _get_next = lambda: self.list(
                    provider=provider,
                    page_number=page_number + 1,
                    page_size=page_size,
                    ascending_order=ascending_order,
                    request_options=request_options,
                )
                _items = _parsed_response.voices_page
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            if _response.status_code == 400:
                raise BadRequestError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self, *, generation_id: str, name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> ReturnVoice:
        """
        Creates a new voice from a specified TTS generation ID and saves it to your **Voice Library**. This allows for consistent speech style and prosody across multiple requests.

        Parameters
        ----------
        generation_id : str
            A unique ID associated with this TTS generation that can be used as context for generating consistent speech style and prosody across multiple requests.

        name : str
            Name of the voice in the `Voice Library`.

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

        Returns
        -------
        ReturnVoice
            Successful Response

        Examples
        --------
        from hume import HumeClient

        client = HumeClient(
            api_key="YOUR_API_KEY",
        )
        client.tts.voices.create(
            generation_id="795c949a-1510-4a80-9646-7d0863b023ab",
            name="David Hume",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="POST",
            json={
                "generation_id": generation_id,
                "name": name,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ReturnVoice,
                    parse_obj_as(
                        type_=ReturnVoice,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete(self, *, name: str, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Removes a custom voice from your **Voice Library**.

        Parameters
        ----------
        name : str
            Name of the voice to delete

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

        Returns
        -------
        None

        Examples
        --------
        from hume import HumeClient

        client = HumeClient(
            api_key="YOUR_API_KEY",
        )
        client.tts.voices.delete(
            name="David Hume",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="DELETE",
            params={
                "name": name,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 400:
                raise BadRequestError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def list(
        self,
        *,
        provider: VoiceProvider,
        page_number: typing.Optional[int] = None,
        page_size: typing.Optional[int] = None,
        ascending_order: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[ReturnVoice]:
        """
        Lists voices in your **Voice Library**. Set provider to `HUME_AI` to list Hume's preset voices, or to `CUSTOM_VOICE` to a custom voice created in your account.

        Parameters
        ----------
        provider : VoiceProvider
            Specifies whether to return custom voices created in your account or shared voices provided by Hume

        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]

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

        Returns
        -------
        AsyncPager[ReturnVoice]
            Success

        Examples
        --------
        import asyncio

        from hume import AsyncHumeClient

        client = AsyncHumeClient(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            response = await client.tts.voices.list(
                provider="CUSTOM_VOICE",
            )
            async for item in response:
                yield item
            # alternatively, you can paginate page-by-page
            async for page in response.iter_pages():
                yield page


        asyncio.run(main())
        """
        page_number = page_number if page_number is not None else 1
        _response = await self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="GET",
            params={
                "provider": provider,
                "page_number": page_number,
                "page_size": page_size,
                "ascending_order": ascending_order,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ReturnPagedVoices,
                    parse_obj_as(
                        type_=ReturnPagedVoices,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = True
                _get_next = lambda: self.list(
                    provider=provider,
                    page_number=page_number + 1,
                    page_size=page_size,
                    ascending_order=ascending_order,
                    request_options=request_options,
                )
                _items = _parsed_response.voices_page
                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            if _response.status_code == 400:
                raise BadRequestError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self, *, generation_id: str, name: str, request_options: typing.Optional[RequestOptions] = None
    ) -> ReturnVoice:
        """
        Creates a new voice from a specified TTS generation ID and saves it to your **Voice Library**. This allows for consistent speech style and prosody across multiple requests.

        Parameters
        ----------
        generation_id : str
            A unique ID associated with this TTS generation that can be used as context for generating consistent speech style and prosody across multiple requests.

        name : str
            Name of the voice in the `Voice Library`.

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

        Returns
        -------
        ReturnVoice
            Successful Response

        Examples
        --------
        import asyncio

        from hume import AsyncHumeClient

        client = AsyncHumeClient(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.tts.voices.create(
                generation_id="795c949a-1510-4a80-9646-7d0863b023ab",
                name="David Hume",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="POST",
            json={
                "generation_id": generation_id,
                "name": name,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ReturnVoice,
                    parse_obj_as(
                        type_=ReturnVoice,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete(self, *, name: str, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Removes a custom voice from your **Voice Library**.

        Parameters
        ----------
        name : str
            Name of the voice to delete

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from hume import AsyncHumeClient

        client = AsyncHumeClient(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.tts.voices.delete(
                name="David Hume",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v0/tts/voices",
            method="DELETE",
            params={
                "name": name,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 400:
                raise BadRequestError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
