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

import typing
import urllib.parse
from contextlib import asynccontextmanager, contextmanager

import websockets.sync.client as websockets_sync_client
from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.jsonable_encoder import jsonable_encoder
from ...core.query_encoder import encode_query
from ...core.remove_none_from_dict import remove_none_from_dict
from ...core.request_options import RequestOptions
from ...core.websocket_compat import InvalidWebSocketStatus, get_status_code
from ..types.audio_format_type import AudioFormatType
from ..types.octave_version import OctaveVersion
from ..types.timestamp_type import TimestampType
from .raw_client import AsyncRawStreamInputClient, RawStreamInputClient
from .socket_client import AsyncStreamInputSocketClient, StreamInputSocketClient

try:
    from websockets.legacy.client import connect as websockets_client_connect  # type: ignore
except ImportError:
    from websockets import connect as websockets_client_connect  # type: ignore


class StreamInputClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawStreamInputClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawStreamInputClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawStreamInputClient
        """
        return self._raw_client

    @contextmanager
    def connect(
        self,
        *,
        access_token: typing.Optional[str] = None,
        context_generation_id: typing.Optional[str] = None,
        format_type: typing.Optional[AudioFormatType] = None,
        include_timestamp_types: typing.Optional[typing.Union[TimestampType, typing.Sequence[TimestampType]]] = None,
        instant_mode: typing.Optional[bool] = None,
        no_binary: typing.Optional[bool] = None,
        strip_headers: typing.Optional[bool] = None,
        version: typing.Optional[OctaveVersion] = None,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[StreamInputSocketClient]:
        """
        Generate emotionally expressive speech.

        Parameters
        ----------
        access_token : typing.Optional[str]
            Access token used for authenticating the client. If not provided, an `api_key` must be provided to authenticate.

            The access token is generated using both an API key and a Secret key, which provides an additional layer of security compared to using just an API key.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

        context_generation_id : typing.Optional[str]
            The ID of a prior TTS generation to use as context for generating consistent speech style and prosody across multiple requests. Including context may increase audio generation times.

        format_type : typing.Optional[AudioFormatType]
            The format to be used for audio generation.

        include_timestamp_types : typing.Optional[typing.Union[TimestampType, typing.Sequence[TimestampType]]]
            The set of timestamp types to include in the response. Only supported for Octave 2 requests.

        instant_mode : typing.Optional[bool]
            Enables ultra-low latency streaming, significantly reducing the time until the first audio chunk is received. Recommended for real-time applications requiring immediate audio playback. For further details, see our documentation on [instant mode](/docs/text-to-speech-tts/overview#ultra-low-latency-streaming-instant-mode).

        no_binary : typing.Optional[bool]
            If enabled, no binary websocket messages will be sent to the client.

        strip_headers : typing.Optional[bool]
            If enabled, the audio for all the chunks of a generation, once concatenated together, will constitute a single audio file. Otherwise, if disabled, each chunk's audio will be its own audio file, each with its own headers (if applicable).

        version : typing.Optional[OctaveVersion]
            The version of the Octave Model to use. 1 for the legacy model, 2 for the new model.

        api_key : typing.Optional[str]
            API key used for authenticating the client. If not provided, an `access_token` must be provided to authenticate.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

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

        Returns
        -------
        StreamInputSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().tts + "/stream/input"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "access_token": access_token,
                        "context_generation_id": context_generation_id,
                        "format_type": format_type,
                        "include_timestamp_types": include_timestamp_types,
                        "instant_mode": instant_mode,
                        "no_binary": no_binary,
                        "strip_headers": strip_headers,
                        "version": version,
                        "api_key": api_key,
                        **(
                            request_options.get("additional_query_parameters", {}) or {}
                            if request_options is not None
                            else {}
                        ),
                    }
                )
            )
        )
        if _encoded_query_params:
            ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params)
        headers = self._raw_client._client_wrapper.get_headers()
        if request_options and "additional_headers" in request_options:
            headers.update(request_options["additional_headers"])
        try:
            with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol:
                yield StreamInputSocketClient(websocket=protocol)
        except InvalidWebSocketStatus as exc:
            status_code: int = get_status_code(exc)
            if status_code == 401:
                raise ApiError(
                    status_code=status_code,
                    headers=dict(headers),
                    body="Websocket initialized with invalid credentials.",
                )
            raise ApiError(
                status_code=status_code,
                headers=dict(headers),
                body="Unexpected error when initializing websocket connection.",
            )


class AsyncStreamInputClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawStreamInputClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawStreamInputClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawStreamInputClient
        """
        return self._raw_client

    @asynccontextmanager
    async def connect(
        self,
        *,
        access_token: typing.Optional[str] = None,
        context_generation_id: typing.Optional[str] = None,
        format_type: typing.Optional[AudioFormatType] = None,
        include_timestamp_types: typing.Optional[typing.Union[TimestampType, typing.Sequence[TimestampType]]] = None,
        instant_mode: typing.Optional[bool] = None,
        no_binary: typing.Optional[bool] = None,
        strip_headers: typing.Optional[bool] = None,
        version: typing.Optional[OctaveVersion] = None,
        api_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncStreamInputSocketClient]:
        """
        Generate emotionally expressive speech.

        Parameters
        ----------
        access_token : typing.Optional[str]
            Access token used for authenticating the client. If not provided, an `api_key` must be provided to authenticate.

            The access token is generated using both an API key and a Secret key, which provides an additional layer of security compared to using just an API key.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

        context_generation_id : typing.Optional[str]
            The ID of a prior TTS generation to use as context for generating consistent speech style and prosody across multiple requests. Including context may increase audio generation times.

        format_type : typing.Optional[AudioFormatType]
            The format to be used for audio generation.

        include_timestamp_types : typing.Optional[typing.Union[TimestampType, typing.Sequence[TimestampType]]]
            The set of timestamp types to include in the response. Only supported for Octave 2 requests.

        instant_mode : typing.Optional[bool]
            Enables ultra-low latency streaming, significantly reducing the time until the first audio chunk is received. Recommended for real-time applications requiring immediate audio playback. For further details, see our documentation on [instant mode](/docs/text-to-speech-tts/overview#ultra-low-latency-streaming-instant-mode).

        no_binary : typing.Optional[bool]
            If enabled, no binary websocket messages will be sent to the client.

        strip_headers : typing.Optional[bool]
            If enabled, the audio for all the chunks of a generation, once concatenated together, will constitute a single audio file. Otherwise, if disabled, each chunk's audio will be its own audio file, each with its own headers (if applicable).

        version : typing.Optional[OctaveVersion]
            The version of the Octave Model to use. 1 for the legacy model, 2 for the new model.

        api_key : typing.Optional[str]
            API key used for authenticating the client. If not provided, an `access_token` must be provided to authenticate.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

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

        Returns
        -------
        AsyncStreamInputSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().tts + "/stream/input"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "access_token": access_token,
                        "context_generation_id": context_generation_id,
                        "format_type": format_type,
                        "include_timestamp_types": include_timestamp_types,
                        "instant_mode": instant_mode,
                        "no_binary": no_binary,
                        "strip_headers": strip_headers,
                        "version": version,
                        "api_key": api_key,
                        **(
                            request_options.get("additional_query_parameters", {}) or {}
                            if request_options is not None
                            else {}
                        ),
                    }
                )
            )
        )
        if _encoded_query_params:
            ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params)
        headers = self._raw_client._client_wrapper.get_headers()
        if request_options and "additional_headers" in request_options:
            headers.update(request_options["additional_headers"])
        try:
            async with websockets_client_connect(ws_url, extra_headers=headers) as protocol:
                yield AsyncStreamInputSocketClient(websocket=protocol)
        except InvalidWebSocketStatus as exc:
            status_code: int = get_status_code(exc)
            if status_code == 401:
                raise ApiError(
                    status_code=status_code,
                    headers=dict(headers),
                    body="Websocket initialized with invalid credentials.",
                )
            raise ApiError(
                status_code=status_code,
                headers=dict(headers),
                body="Unexpected error when initializing websocket connection.",
            )
