# 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 ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.orchestrator_pipeline_call_result import OrchestratorPipelineCallResult
from ..types.orchestrator_pipeline_result import OrchestratorPipelineResult
from ..types.text_to_audio_result import TextToAudioResult
from ..types.text_to_audio_type import TextToAudioType

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


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

    def create_text_to_audio(
        self,
        *,
        prompt: str,
        run_id: typing.Optional[int] = None,
        traceparent: typing.Optional[str] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        duration: typing.Optional[float] = OMIT,
        audio_type: typing.Optional[TextToAudioType] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[OrchestratorPipelineCallResult]:
        """
        Parameters
        ----------
        prompt : str
            The text to be converted to audio.

        run_id : typing.Optional[int]

        traceparent : typing.Optional[str]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        duration : typing.Optional[float]
            The desired duration of the audio.

        audio_type : typing.Optional[TextToAudioType]
            The audio type preference.

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

        Returns
        -------
        HttpResponse[OrchestratorPipelineCallResult]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "text-to-sound",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "prompt": prompt,
                "duration": duration,
                "audio_type": audio_type,
            },
            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(
                    OrchestratorPipelineCallResult,
                    parse_obj_as(
                        type_=OrchestratorPipelineCallResult,  # 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_text_to_audio_status(
        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"text-to-sound/{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)

    @contextlib.contextmanager
    def get_text_to_audio_result(
        self,
        run_id: typing.Optional[int],
        *,
        output_type: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]:
        """
        Retrieve the Text-to-Audio (TTA) result for a given run.

        This endpoint validates the provided run ID and retrieves the associated
        Text-to-Audio output. It supports two output formats:
        - RAW_BYTES: Streams the audio file in WAV format.
        - FILE_URL: Returns a pre-signed URL for downloading the audio file.

        The endpoint ensures that the run type is valid for Text-to-Audio processing
        and that the storage preferences are applied accordingly.

        Args:
            run_id (int): Unique identifier for the TTA run.
            traceparent (Optional[str]): Trace header for distributed tracing.
            api_key_obj (dict): API key object containing authentication and storage preferences.
            output_type (OutputType): Desired output format. Defaults to RAW_BYTES.

        Returns:
            StreamingResponse | GetTTAOut:
                - StreamingResponse: If output_type is RAW_BYTES, a streaming response with the audio in WAV format.
                - GetTTAOut: If output_type is FILE_URL, a pre-signed URL to access the audio file.

        Raises:
            HTTPException:
                - 400 BAD REQUEST: If the run type is invalid for a TTA run.
                - 500 INTERNAL SERVER ERROR: If the audio file cannot be fetched or streamed.

        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. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.Iterator[HttpResponse[typing.Iterator[bytes]]]
            Successful Response
        """
        with self._client_wrapper.httpx_client.stream(
            f"text-to-sound-result/{jsonable_encoder(run_id)}",
            method="GET",
            params={
                "output_type": output_type,
            },
            request_options=request_options,
        ) 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()
                    _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 get_text_to_sound_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, TextToAudioResult]]:
        """
        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, TextToAudioResult]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "text-to-sound-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, TextToAudioResult],
                    parse_obj_as(
                        type_=typing.Dict[str, TextToAudioResult],  # 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 AsyncRawTextToAudioClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create_text_to_audio(
        self,
        *,
        prompt: str,
        run_id: typing.Optional[int] = None,
        traceparent: typing.Optional[str] = None,
        project_name: typing.Optional[str] = OMIT,
        project_description: typing.Optional[str] = OMIT,
        folder_id: typing.Optional[int] = OMIT,
        duration: typing.Optional[float] = OMIT,
        audio_type: typing.Optional[TextToAudioType] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[OrchestratorPipelineCallResult]:
        """
        Parameters
        ----------
        prompt : str
            The text to be converted to audio.

        run_id : typing.Optional[int]

        traceparent : typing.Optional[str]

        project_name : typing.Optional[str]

        project_description : typing.Optional[str]

        folder_id : typing.Optional[int]

        duration : typing.Optional[float]
            The desired duration of the audio.

        audio_type : typing.Optional[TextToAudioType]
            The audio type preference.

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

        Returns
        -------
        AsyncHttpResponse[OrchestratorPipelineCallResult]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "text-to-sound",
            method="POST",
            params={
                "run_id": run_id,
            },
            json={
                "project_name": project_name,
                "project_description": project_description,
                "folder_id": folder_id,
                "prompt": prompt,
                "duration": duration,
                "audio_type": audio_type,
            },
            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(
                    OrchestratorPipelineCallResult,
                    parse_obj_as(
                        type_=OrchestratorPipelineCallResult,  # 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_text_to_audio_status(
        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"text-to-sound/{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)

    @contextlib.asynccontextmanager
    async def get_text_to_audio_result(
        self,
        run_id: typing.Optional[int],
        *,
        output_type: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]:
        """
        Retrieve the Text-to-Audio (TTA) result for a given run.

        This endpoint validates the provided run ID and retrieves the associated
        Text-to-Audio output. It supports two output formats:
        - RAW_BYTES: Streams the audio file in WAV format.
        - FILE_URL: Returns a pre-signed URL for downloading the audio file.

        The endpoint ensures that the run type is valid for Text-to-Audio processing
        and that the storage preferences are applied accordingly.

        Args:
            run_id (int): Unique identifier for the TTA run.
            traceparent (Optional[str]): Trace header for distributed tracing.
            api_key_obj (dict): API key object containing authentication and storage preferences.
            output_type (OutputType): Desired output format. Defaults to RAW_BYTES.

        Returns:
            StreamingResponse | GetTTAOut:
                - StreamingResponse: If output_type is RAW_BYTES, a streaming response with the audio in WAV format.
                - GetTTAOut: If output_type is FILE_URL, a pre-signed URL to access the audio file.

        Raises:
            HTTPException:
                - 400 BAD REQUEST: If the run type is invalid for a TTA run.
                - 500 INTERNAL SERVER ERROR: If the audio file cannot be fetched or streamed.

        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. You can pass in configuration such as `chunk_size`, and more to customize the request and response.

        Returns
        -------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]
            Successful Response
        """
        async with self._client_wrapper.httpx_client.stream(
            f"text-to-sound-result/{jsonable_encoder(run_id)}",
            method="GET",
            params={
                "output_type": output_type,
            },
            request_options=request_options,
        ) 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()
                    _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 get_text_to_sound_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, TextToAudioResult]]:
        """
        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, TextToAudioResult]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "text-to-sound-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, TextToAudioResult],
                    parse_obj_as(
                        type_=typing.Dict[str, TextToAudioResult],  # 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)
