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

import typing
from contextlib import asynccontextmanager, contextmanager

import httpx
import websockets
import websockets.sync.client as websockets_sync_client
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from .raw_client import AsyncRawSpeechToTextTranslateStreamingClient, RawSpeechToTextTranslateStreamingClient
from .socket_client import AsyncSpeechToTextTranslateStreamingSocketClient, SpeechToTextTranslateStreamingSocketClient
from .types.speech_to_text_translate_streaming_high_vad_sensitivity import (
    SpeechToTextTranslateStreamingHighVadSensitivity,
)
from .types.speech_to_text_translate_streaming_model import SpeechToTextTranslateStreamingModel
from .types.speech_to_text_translate_streaming_vad_signals import SpeechToTextTranslateStreamingVadSignals


class SpeechToTextTranslateStreamingClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawSpeechToTextTranslateStreamingClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawSpeechToTextTranslateStreamingClient
        """
        return self._raw_client

    @contextmanager
    def connect(
        self,
        *,
        model: typing.Optional[SpeechToTextTranslateStreamingModel] = None,
        high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None,
        vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None,
        api_subscription_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[SpeechToTextTranslateStreamingSocketClient]:
        """
        WebSocket channel for real-time speech to text streaming with English translation

        Parameters
        ----------
        model : typing.Optional[SpeechToTextTranslateStreamingModel]
            Speech to text model to use (defaults to "saaras:v2.5" if not specified)

        high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity]
            Enable high VAD (Voice Activity Detection) sensitivity

        vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals]
            Enable VAD signals in response

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

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

        Returns
        -------
        SpeechToTextTranslateStreamingSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text-translate/ws"
        query_params = httpx.QueryParams()
        if model is not None:
            query_params = query_params.add("model", model)
        if high_vad_sensitivity is not None:
            query_params = query_params.add("high_vad_sensitivity", high_vad_sensitivity)
        if vad_signals is not None:
            query_params = query_params.add("vad_signals", vad_signals)
        ws_url = ws_url + f"?{query_params}"
        headers = self._raw_client._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 SpeechToTextTranslateStreamingSocketClient(websocket=protocol)
        except websockets.exceptions.InvalidStatusCode as exc:
            status_code: int = exc.status_code
            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 AsyncSpeechToTextTranslateStreamingClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawSpeechToTextTranslateStreamingClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawSpeechToTextTranslateStreamingClient
        """
        return self._raw_client

    @asynccontextmanager
    async def connect(
        self,
        *,
        model: typing.Optional[SpeechToTextTranslateStreamingModel] = None,
        high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None,
        vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None,
        api_subscription_key: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncSpeechToTextTranslateStreamingSocketClient]:
        """
        WebSocket channel for real-time speech to text streaming with English translation

        Parameters
        ----------
        model : typing.Optional[SpeechToTextTranslateStreamingModel]
            Speech to text model to use (defaults to "saaras:v2.5" if not specified)

        high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity]
            Enable high VAD (Voice Activity Detection) sensitivity

        vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals]
            Enable VAD signals in response

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

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

        Returns
        -------
        AsyncSpeechToTextTranslateStreamingSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text-translate/ws"
        query_params = httpx.QueryParams()
        if model is not None:
            query_params = query_params.add("model", model)
        if high_vad_sensitivity is not None:
            query_params = query_params.add("high_vad_sensitivity", high_vad_sensitivity)
        if vad_signals is not None:
            query_params = query_params.add("vad_signals", vad_signals)
        ws_url = ws_url + f"?{query_params}"
        headers = self._raw_client._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.connect(ws_url, extra_headers=headers) as protocol:
                yield AsyncSpeechToTextTranslateStreamingSocketClient(websocket=protocol)
        except websockets.exceptions.InvalidStatusCode as exc:
            status_code: int = exc.status_code
            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.",
            )
