# 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 AsyncV2SocketClient, V2SocketClient

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

    @contextmanager
    def connect(
        self,
        *,
        model: str,
        encoding: typing.Optional[str] = None,
        sample_rate: typing.Optional[str] = None,
        eager_eot_threshold: typing.Optional[str] = None,
        eot_threshold: typing.Optional[str] = None,
        eot_timeout_ms: typing.Optional[str] = None,
        keyterm: typing.Optional[str] = None,
        mip_opt_out: typing.Optional[str] = None,
        tag: typing.Optional[str] = None,
        authorization: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[V2SocketClient]:
        """
        Real-time conversational speech recognition with contextual turn detection
        for natural voice conversations

        Parameters
        ----------
        model : str

        encoding : typing.Optional[str]

        sample_rate : typing.Optional[str]

        eager_eot_threshold : typing.Optional[str]

        eot_threshold : typing.Optional[str]

        eot_timeout_ms : typing.Optional[str]

        keyterm : typing.Optional[str]

        mip_opt_out : typing.Optional[str]

        tag : typing.Optional[str]

        authorization : typing.Optional[str]
            Use your API key for authentication, or alternatively generate a [temporary token](/guides/fundamentals/token-based-authentication) and pass it via the `token` query parameter.

            **Example:** `token %DEEPGRAM_API_KEY%` or `bearer %DEEPGRAM_TOKEN%`

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

        Returns
        -------
        V2SocketClient
        """
        ws_url = self._client_wrapper.get_environment().production + "/v2/listen"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "model": model,
                        "encoding": encoding,
                        "sample_rate": sample_rate,
                        "eager_eot_threshold": eager_eot_threshold,
                        "eot_threshold": eot_threshold,
                        "eot_timeout_ms": eot_timeout_ms,
                        "keyterm": keyterm,
                        "mip_opt_out": mip_opt_out,
                        "tag": tag,
                        **(
                            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 authorization is not None:
            headers["Authorization"] = str(authorization)
        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 V2SocketClient(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 AsyncRawV2Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @asynccontextmanager
    async def connect(
        self,
        *,
        model: str,
        encoding: typing.Optional[str] = None,
        sample_rate: typing.Optional[str] = None,
        eager_eot_threshold: typing.Optional[str] = None,
        eot_threshold: typing.Optional[str] = None,
        eot_timeout_ms: typing.Optional[str] = None,
        keyterm: typing.Optional[str] = None,
        mip_opt_out: typing.Optional[str] = None,
        tag: typing.Optional[str] = None,
        authorization: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncV2SocketClient]:
        """
        Real-time conversational speech recognition with contextual turn detection
        for natural voice conversations

        Parameters
        ----------
        model : str

        encoding : typing.Optional[str]

        sample_rate : typing.Optional[str]

        eager_eot_threshold : typing.Optional[str]

        eot_threshold : typing.Optional[str]

        eot_timeout_ms : typing.Optional[str]

        keyterm : typing.Optional[str]

        mip_opt_out : typing.Optional[str]

        tag : typing.Optional[str]

        authorization : typing.Optional[str]
            Use your API key for authentication, or alternatively generate a [temporary token](/guides/fundamentals/token-based-authentication) and pass it via the `token` query parameter.

            **Example:** `token %DEEPGRAM_API_KEY%` or `bearer %DEEPGRAM_TOKEN%`

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

        Returns
        -------
        AsyncV2SocketClient
        """
        ws_url = self._client_wrapper.get_environment().production + "/v2/listen"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "model": model,
                        "encoding": encoding,
                        "sample_rate": sample_rate,
                        "eager_eot_threshold": eager_eot_threshold,
                        "eot_threshold": eot_threshold,
                        "eot_timeout_ms": eot_timeout_ms,
                        "keyterm": keyterm,
                        "mip_opt_out": mip_opt_out,
                        "tag": tag,
                        **(
                            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 authorization is not None:
            headers["Authorization"] = str(authorization)
        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 AsyncV2SocketClient(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.",
            )
