# 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 .socket_client import AsyncTextToSpeechStreamingSocketClient, TextToSpeechStreamingSocketClient
from .types.text_to_speech_streaming_model import TextToSpeechStreamingModel
from .types.text_to_speech_streaming_send_completion_event import TextToSpeechStreamingSendCompletionEvent

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 RawTextToSpeechStreamingClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextmanager
    def connect(
        self,
        *,
        model: typing.Optional[TextToSpeechStreamingModel] = None,
        send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None,
        api_subscription_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[TextToSpeechStreamingSocketClient]:
        """
        WebSocket channel for real-time TTS synthesis.

        **Note:** This API Reference page is provided for informational purposes only.
        The Try It playground may not provide the best experience for streaming audio.
        For optimal streaming performance, please use the SDK or implement your own WebSocket client.

        **Model-Specific Notes:**
        - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz.
        - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled.

        Parameters
        ----------
        model : typing.Optional[TextToSpeechStreamingModel]
            Text to speech model to use.
            - **bulbul:v2** (default): Standard TTS model with pitch/loudness support
            - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness)

        send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent]
            Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated.

        api_subscription_key : typing.Optional[str]
            API subscription key for authentication

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

        Returns
        -------
        TextToSpeechStreamingSocketClient
        """
        ws_url = self._client_wrapper.get_environment().production + "/text-to-speech/ws"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "model": model,
                        "send_completion_event": send_completion_event,
                        **(
                            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._client_wrapper.get_headers()
        if api_subscription_key is not None:
            headers["Api-Subscription-Key"] = str(api_subscription_key)
        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 TextToSpeechStreamingSocketClient(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 AsyncRawTextToSpeechStreamingClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @asynccontextmanager
    async def connect(
        self,
        *,
        model: typing.Optional[TextToSpeechStreamingModel] = None,
        send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None,
        api_subscription_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncTextToSpeechStreamingSocketClient]:
        """
        WebSocket channel for real-time TTS synthesis.

        **Note:** This API Reference page is provided for informational purposes only.
        The Try It playground may not provide the best experience for streaming audio.
        For optimal streaming performance, please use the SDK or implement your own WebSocket client.

        **Model-Specific Notes:**
        - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz.
        - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled.

        Parameters
        ----------
        model : typing.Optional[TextToSpeechStreamingModel]
            Text to speech model to use.
            - **bulbul:v2** (default): Standard TTS model with pitch/loudness support
            - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness)

        send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent]
            Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated.

        api_subscription_key : typing.Optional[str]
            API subscription key for authentication

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

        Returns
        -------
        AsyncTextToSpeechStreamingSocketClient
        """
        ws_url = self._client_wrapper.get_environment().production + "/text-to-speech/ws"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "model": model,
                        "send_completion_event": send_completion_event,
                        **(
                            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._client_wrapper.get_headers()
        if api_subscription_key is not None:
            headers["Api-Subscription-Key"] = str(api_subscription_key)
        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 AsyncTextToSpeechStreamingSocketClient(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.",
            )
