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

import typing
from contextlib import asynccontextmanager, contextmanager

import httpx
import websockets.exceptions
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 AsyncRawV2Client, RawV2Client
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 V2Client:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawV2Client(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawV2Client
        """
        return self._raw_client

    @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._raw_client._client_wrapper.get_environment().production + "/v2/listen"
        query_params = httpx.QueryParams()
        if model is not None:
            query_params = query_params.add("model", model)
        if encoding is not None:
            query_params = query_params.add("encoding", encoding)
        if sample_rate is not None:
            query_params = query_params.add("sample_rate", sample_rate)
        if eager_eot_threshold is not None:
            query_params = query_params.add("eager_eot_threshold", eager_eot_threshold)
        if eot_threshold is not None:
            query_params = query_params.add("eot_threshold", eot_threshold)
        if eot_timeout_ms is not None:
            query_params = query_params.add("eot_timeout_ms", eot_timeout_ms)
        if keyterm is not None:
            query_params = query_params.add("keyterm", keyterm)
        if mip_opt_out is not None:
            query_params = query_params.add("mip_opt_out", mip_opt_out)
        if tag is not None:
            query_params = query_params.add("tag", tag)
        ws_url = ws_url + f"?{query_params}"
        headers = self._raw_client._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 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 AsyncV2Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawV2Client(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawV2Client
        """
        return self._raw_client

    @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._raw_client._client_wrapper.get_environment().production + "/v2/listen"
        query_params = httpx.QueryParams()
        if model is not None:
            query_params = query_params.add("model", model)
        if encoding is not None:
            query_params = query_params.add("encoding", encoding)
        if sample_rate is not None:
            query_params = query_params.add("sample_rate", sample_rate)
        if eager_eot_threshold is not None:
            query_params = query_params.add("eager_eot_threshold", eager_eot_threshold)
        if eot_threshold is not None:
            query_params = query_params.add("eot_threshold", eot_threshold)
        if eot_timeout_ms is not None:
            query_params = query_params.add("eot_timeout_ms", eot_timeout_ms)
        if keyterm is not None:
            query_params = query_params.add("keyterm", keyterm)
        if mip_opt_out is not None:
            query_params = query_params.add("mip_opt_out", mip_opt_out)
        if tag is not None:
            query_params = query_params.add("tag", tag)
        ws_url = ws_url + f"?{query_params}"
        headers = self._raw_client._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 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.",
            )
