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

import contextlib
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.create_tts_out import CreateTtsOut
from ..types.gender import Gender
from ..types.http_validation_error import HttpValidationError
from ..types.languages import Languages
from ..types.orchestrator_pipeline_result import OrchestratorPipelineResult
from ..types.stream_tts_inference_options import StreamTtsInferenceOptions
from ..types.stream_tts_output_configuration import StreamTtsOutputConfiguration
from ..types.stream_tts_voice_settings import StreamTtsVoiceSettings
from .baseten import async_baseten_tts, baseten_tts
from .types.create_stream_tts_request_payload_language import CreateStreamTtsRequestPayloadLanguage
from .types.create_stream_tts_request_payload_speech_model import CreateStreamTtsRequestPayloadSpeechModel
from .types.get_tts_results_tts_results_post_response_value import GetTtsResultsTtsResultsPostResponseValue
from .types.get_tts_run_info_tts_result_run_id_get_response import GetTtsRunInfoTtsResultRunIdGetResponse

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


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

    @contextlib.contextmanager
    def tts(
        self,
        *,
        text: str,
        language: CreateStreamTtsRequestPayloadLanguage,
        voice_id: typing.Optional[int] = OMIT,
        speech_model: typing.Optional[CreateStreamTtsRequestPayloadSpeechModel] = OMIT,
        user_instructions: typing.Optional[str] = OMIT,
        enhance_named_entities_pronunciation: typing.Optional[bool] = OMIT,
        output_configuration: typing.Optional[StreamTtsOutputConfiguration] = OMIT,
        voice_settings: typing.Optional[StreamTtsVoiceSettings] = OMIT,
        inference_options: typing.Optional[StreamTtsInferenceOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]:
        """
        Parameters
        ----------
        text : str

        language : CreateStreamTtsRequestPayloadLanguage

        voice_id : int

        speech_model : typing.Optional[CreateStreamTtsRequestPayloadSpeechModel]

        user_instructions : typing.Optional[str]

        enhance_named_entities_pronunciation : typing.Optional[bool]

        output_configuration : typing.Optional[StreamTtsOutputConfiguration]

        voice_settings : typing.Optional[StreamTtsVoiceSettings]

        inference_options : typing.Optional[StreamTtsInferenceOptions]

        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.

        Returns
        -------
        typing.Iterator[HttpResponse[typing.Iterator[bytes]]]
            Streaming audio response
        """
        if self._client_wrapper.tts_provider is None and (voice_id is OMIT or voice_id is None):
             raise ValueError("voice_id is required when using the default Camb.ai provider.")

        if self._client_wrapper.tts_provider == "baseten":
            if speech_model == "mars-flash":
                with baseten_tts(
                    self._client_wrapper,
                    text=text,
                    language=language,
                    voice_id=voice_id,
                    speech_model=speech_model,
                    user_instructions=user_instructions,
                    enhance_named_entities_pronunciation=enhance_named_entities_pronunciation,
                    output_configuration=output_configuration,
                    voice_settings=voice_settings,
                    inference_options=inference_options,
                    request_options=request_options,
                ) as r:
                    yield r
                return
            else:
                raise ValueError(f"{self._client_wrapper.tts_provider} provider can only be used with 'mars-pro' speech model.")

        with self._client_wrapper.httpx_client.stream(
            "tts-stream",
            method="POST",
            json={
                "text": text,
                "language": language,
                "voice_id": voice_id,
                "speech_model": speech_model,
                "user_instructions": user_instructions,
                "enhance_named_entities_pronunciation": enhance_named_entities_pronunciation,
                "output_configuration": convert_and_respect_annotation_metadata(
                    object_=output_configuration, annotation=StreamTtsOutputConfiguration, direction="write"
                ),
                "voice_settings": convert_and_respect_annotation_metadata(
                    object_=voice_settings, annotation=StreamTtsVoiceSettings, direction="write"
                ),
                "inference_options": convert_and_respect_annotation_metadata(
                    object_=inference_options, annotation=StreamTtsInferenceOptions, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[bytes]]:
                try:
                    if 200 <= _response.status_code < 300:
                        _chunk_size = request_options.get("chunk_size", None) if request_options is not None else None
                        return HttpResponse(
                            response=_response, data=(_chunk for _chunk in _response.iter_bytes(chunk_size=_chunk_size))
                        )
                    _response.read()
                    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)

            yield _stream()

    def create_tts(
        self,
        *,
        text: str,
        voice_id: int,
        language: Languages,
        run_id: typing.Optional[int] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        gender: typing.Optional[Gender] = OMIT,
        age: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[CreateTtsOut]:
        """
        Parameters
        ----------
        text : str

        voice_id : int

        language : Languages

        run_id : typing.Optional[int]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        gender : typing.Optional[Gender]

        age : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[CreateTtsOut]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "tts",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "text": text,
                "voice_id": voice_id,
                "language": language,
                "gender": gender,
                "age": age,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateTtsOut,
                    parse_obj_as(
                        type_=CreateTtsOut,  # 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 get_tts_result(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[OrchestratorPipelineResult]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[OrchestratorPipelineResult]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"tts/{jsonable_encoder(task_id)}",
            method="GET",
            params={
                "run_id": run_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    OrchestratorPipelineResult,
                    parse_obj_as(
                        type_=OrchestratorPipelineResult,  # 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 get_tts_run_info(
        self,
        run_id: typing.Optional[int],
        *,
        output_type: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetTtsRunInfoTtsResultRunIdGetResponse]:
        """
        Retrieves the result of a Text To Speech (TTS) run.

        This endpoint validates the provided `run_id` and fetches the corresponding TTS-generated audio.
        The user must have valid access to the run. The function supports two output formats:
        - `RAW_BYTES`: Streams the audio file directly.
        - `FILE_URL`: Returns a pre-signed URL to download the audio file.

        Args:
            run_id (int): Unique identifier for the TTS run.
            api_key_obj (dict): API key object used for authentication and storage preferences.
            traceparent (Optional[str]): Traceparent header for distributed tracing.
            output_type (OutputType, optional): Determines the output format. Defaults to `RAW_BYTES`.

        Returns:
            StreamingResponse | GetTTSOut:
                - If `output_type = RAW_BYTES`: A streaming response containing the TTS-generated audio in FLAC format.
                - If `output_type = FILE_URL`: A URL pointing to the stored TTS-generated audio file.

        Raises:
            HTTPException:
                - 400 BAD REQUEST if the run ID is invalid or does not belong to a TTS process.
                - 500 INTERNAL SERVER ERROR if fetching or streaming the audio fails.

        Assumptions:
            - The user has valid access to the `run_id`.
            - The `run_id` corresponds to a valid TTS run.
            - There is only **one** dialogue associated with the given `run_id`.

        Parameters
        ----------
        run_id : typing.Optional[int]

        output_type : typing.Optional[str]
            Output format for the Text To Speech result

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

        Returns
        -------
        HttpResponse[GetTtsRunInfoTtsResultRunIdGetResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"tts-result/{jsonable_encoder(run_id)}",
            method="GET",
            params={
                "output_type": output_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetTtsRunInfoTtsResultRunIdGetResponse,
                    parse_obj_as(
                        type_=GetTtsRunInfoTtsResultRunIdGetResponse,  # 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 get_tts_results(
        self,
        *,
        run_ids: typing.Sequence[int],
        run_id: typing.Optional[int] = None,
        traceparent: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue]]:
        """
        Parameters
        ----------
        run_ids : typing.Sequence[int]

        run_id : typing.Optional[int]

        traceparent : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "tts-results",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "run_ids": run_ids,
            },
            headers={
                "content-type": "application/json",
                "traceparent": str(traceparent) if traceparent is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue],
                    parse_obj_as(
                        type_=typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue],  # 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 get_tts_result_discord(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[OrchestratorPipelineResult]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

        Returns
        -------
        HttpResponse[OrchestratorPipelineResult]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"discord/tts/{jsonable_encoder(task_id)}",
            method="GET",
            params={
                "run_id": run_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    OrchestratorPipelineResult,
                    parse_obj_as(
                        type_=OrchestratorPipelineResult,  # 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 AsyncRawTextToSpeechClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.asynccontextmanager
    async def tts(
        self,
        *,
        text: str,
        language: CreateStreamTtsRequestPayloadLanguage,
        voice_id: typing.Optional[int] = OMIT,
        speech_model: typing.Optional[CreateStreamTtsRequestPayloadSpeechModel] = OMIT,
        user_instructions: typing.Optional[str] = OMIT,
        enhance_named_entities_pronunciation: typing.Optional[bool] = OMIT,
        output_configuration: typing.Optional[StreamTtsOutputConfiguration] = OMIT,
        voice_settings: typing.Optional[StreamTtsVoiceSettings] = OMIT,
        inference_options: typing.Optional[StreamTtsInferenceOptions] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]:
        """
        Parameters
        ----------
        text : str

        language : CreateStreamTtsRequestPayloadLanguage

        voice_id : int

        speech_model : typing.Optional[CreateStreamTtsRequestPayloadSpeechModel]

        user_instructions : typing.Optional[str]

        enhance_named_entities_pronunciation : typing.Optional[bool]

        output_configuration : typing.Optional[StreamTtsOutputConfiguration]

        voice_settings : typing.Optional[StreamTtsVoiceSettings]

        inference_options : typing.Optional[StreamTtsInferenceOptions]

        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.

        Returns
        -------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]
            Streaming audio response
        """
        if self._client_wrapper.tts_provider is None and (voice_id is OMIT or voice_id is None):
             raise ValueError("voice_id is required when using the default Camb.ai provider.")

        if self._client_wrapper.tts_provider == "baseten":
            if speech_model == "mars-flash":
                async with async_baseten_tts(
                    self._client_wrapper,
                    text=text,
                    language=language,
                    voice_id=voice_id,
                    speech_model=speech_model,
                    user_instructions=user_instructions,
                    enhance_named_entities_pronunciation=enhance_named_entities_pronunciation,
                    output_configuration=output_configuration,
                    voice_settings=voice_settings,
                    inference_options=inference_options,
                    request_options=request_options,
                ) as r:
                    yield r
                return
            else:
                raise ValueError("Baseten provider can only be used with 'mars-pro' speech model.")

        async with self._client_wrapper.httpx_client.stream(
            "tts-stream",
            method="POST",
            json={
                "text": text,
                "language": language,
                "voice_id": voice_id,
                "speech_model": speech_model,
                "user_instructions": user_instructions,
                "enhance_named_entities_pronunciation": enhance_named_entities_pronunciation,
                "output_configuration": convert_and_respect_annotation_metadata(
                    object_=output_configuration, annotation=StreamTtsOutputConfiguration, direction="write"
                ),
                "voice_settings": convert_and_respect_annotation_metadata(
                    object_=voice_settings, annotation=StreamTtsVoiceSettings, direction="write"
                ),
                "inference_options": convert_and_respect_annotation_metadata(
                    object_=inference_options, annotation=StreamTtsInferenceOptions, direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[bytes]]:
                try:
                    if 200 <= _response.status_code < 300:
                        _chunk_size = request_options.get("chunk_size", None) if request_options is not None else None
                        return AsyncHttpResponse(
                            response=_response,
                            data=(_chunk async for _chunk in _response.aiter_bytes(chunk_size=_chunk_size)),
                        )
                    await _response.aread()
                    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)

            yield await _stream()

    async def create_tts(
        self,
        *,
        text: str,
        voice_id: int,
        language: Languages,
        run_id: typing.Optional[int] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        gender: typing.Optional[Gender] = OMIT,
        age: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[CreateTtsOut]:
        """
        Parameters
        ----------
        text : str

        voice_id : int

        language : Languages

        run_id : typing.Optional[int]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        gender : typing.Optional[Gender]

        age : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[CreateTtsOut]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tts",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "text": text,
                "voice_id": voice_id,
                "language": language,
                "gender": gender,
                "age": age,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    CreateTtsOut,
                    parse_obj_as(
                        type_=CreateTtsOut,  # 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 get_tts_result(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[OrchestratorPipelineResult]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

        Returns
        -------
        AsyncHttpResponse[OrchestratorPipelineResult]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"tts/{jsonable_encoder(task_id)}",
            method="GET",
            params={
                "run_id": run_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    OrchestratorPipelineResult,
                    parse_obj_as(
                        type_=OrchestratorPipelineResult,  # 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 get_tts_run_info(
        self,
        run_id: typing.Optional[int],
        *,
        output_type: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetTtsRunInfoTtsResultRunIdGetResponse]:
        """
        Retrieves the result of a Text To Speech (TTS) run.

        This endpoint validates the provided `run_id` and fetches the corresponding TTS-generated audio.
        The user must have valid access to the run. The function supports two output formats:
        - `RAW_BYTES`: Streams the audio file directly.
        - `FILE_URL`: Returns a pre-signed URL to download the audio file.

        Args:
            run_id (int): Unique identifier for the TTS run.
            api_key_obj (dict): API key object used for authentication and storage preferences.
            traceparent (Optional[str]): Traceparent header for distributed tracing.
            output_type (OutputType, optional): Determines the output format. Defaults to `RAW_BYTES`.

        Returns:
            StreamingResponse | GetTTSOut:
                - If `output_type = RAW_BYTES`: A streaming response containing the TTS-generated audio in FLAC format.
                - If `output_type = FILE_URL`: A URL pointing to the stored TTS-generated audio file.

        Raises:
            HTTPException:
                - 400 BAD REQUEST if the run ID is invalid or does not belong to a TTS process.
                - 500 INTERNAL SERVER ERROR if fetching or streaming the audio fails.

        Assumptions:
            - The user has valid access to the `run_id`.
            - The `run_id` corresponds to a valid TTS run.
            - There is only **one** dialogue associated with the given `run_id`.

        Parameters
        ----------
        run_id : typing.Optional[int]

        output_type : typing.Optional[str]
            Output format for the Text To Speech result

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

        Returns
        -------
        AsyncHttpResponse[GetTtsRunInfoTtsResultRunIdGetResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"tts-result/{jsonable_encoder(run_id)}",
            method="GET",
            params={
                "output_type": output_type,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetTtsRunInfoTtsResultRunIdGetResponse,
                    parse_obj_as(
                        type_=GetTtsRunInfoTtsResultRunIdGetResponse,  # 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 get_tts_results(
        self,
        *,
        run_ids: typing.Sequence[int],
        run_id: typing.Optional[int] = None,
        traceparent: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue]]:
        """
        Parameters
        ----------
        run_ids : typing.Sequence[int]

        run_id : typing.Optional[int]

        traceparent : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "tts-results",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "run_ids": run_ids,
            },
            headers={
                "content-type": "application/json",
                "traceparent": str(traceparent) if traceparent is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue],
                    parse_obj_as(
                        type_=typing.Dict[str, GetTtsResultsTtsResultsPostResponseValue],  # 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 get_tts_result_discord(
        self,
        task_id: str,
        *,
        run_id: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[OrchestratorPipelineResult]:
        """
        Parameters
        ----------
        task_id : str

        run_id : typing.Optional[int]

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

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