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

import typing
from ..core.client_wrapper import SyncClientWrapper
from .voices.client import VoicesClient
from ..types.voice_options import VoiceOptions
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 ..core.pydantic_utilities import parse_obj_as
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper
from .voices.client import AsyncVoicesClient

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


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

    def generate_internal(
        self,
        *,
        model_id: str,
        text: str,
        voice_id: str,
        voice_options: typing.Optional[VoiceOptions] = OMIT,
        format: typing.Optional[typing.Literal["wav_24000"]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[bytes]:
        """
        Primary text to speech endpoint.

        Parameters
        ----------
        model_id : str
            (required) The model ID to generate speech audio with.

        text : str
            (required) The desired text spoken in the generated audio.

        voice_id : str
            (required) The voice ID to use for generating audio.

        voice_options : typing.Optional[VoiceOptions]

        format : typing.Optional[typing.Literal["wav_24000"]]
            (optional) The audio format of the output audio.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Yields
        ------
        typing.Iterator[bytes]
            Returns a stream of audio bytes.
        """
        with self._client_wrapper.httpx_client.stream(
            "api/v1/audio/text-to-speech",
            method="POST",
            json={
                "model_id": model_id,
                "text": text,
                "voice_id": voice_id,
                "voice_options": convert_and_respect_annotation_metadata(
                    object_=voice_options, annotation=VoiceOptions, direction="write"
                ),
                "format": format,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _chunk_size = (
                        request_options.get("chunk_size", None)
                        if request_options is not None
                        else None
                    )
                    for _chunk in _response.iter_bytes(chunk_size=_chunk_size):
                        yield _chunk
                    return
                _response.read()
                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)


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

    async def generate_internal(
        self,
        *,
        model_id: str,
        text: str,
        voice_id: str,
        voice_options: typing.Optional[VoiceOptions] = OMIT,
        format: typing.Optional[typing.Literal["wav_24000"]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[bytes]:
        """
        Primary text to speech endpoint.

        Parameters
        ----------
        model_id : str
            (required) The model ID to generate speech audio with.

        text : str
            (required) The desired text spoken in the generated audio.

        voice_id : str
            (required) The voice ID to use for generating audio.

        voice_options : typing.Optional[VoiceOptions]

        format : typing.Optional[typing.Literal["wav_24000"]]
            (optional) The audio format of the output audio.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Yields
        ------
        typing.AsyncIterator[bytes]
            Returns a stream of audio bytes.
        """
        async with self._client_wrapper.httpx_client.stream(
            "api/v1/audio/text-to-speech",
            method="POST",
            json={
                "model_id": model_id,
                "text": text,
                "voice_id": voice_id,
                "voice_options": convert_and_respect_annotation_metadata(
                    object_=voice_options, annotation=VoiceOptions, direction="write"
                ),
                "format": format,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _chunk_size = (
                        request_options.get("chunk_size", None)
                        if request_options is not None
                        else None
                    )
                    async for _chunk in _response.aiter_bytes(chunk_size=_chunk_size):
                        yield _chunk
                    return
                await _response.aread()
                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)
