# 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.serialization import convert_and_respect_annotation_metadata
from ...core.websocket_compat import InvalidWebSocketStatus, get_status_code
from ...requests.listen_v2keyterm import ListenV2KeytermParams
from ...types.listen_v2eager_eot_threshold import ListenV2EagerEotThreshold
from ...types.listen_v2encoding import ListenV2Encoding
from ...types.listen_v2eot_threshold import ListenV2EotThreshold
from ...types.listen_v2eot_timeout_ms import ListenV2EotTimeoutMs
from ...types.listen_v2mip_opt_out import ListenV2MipOptOut
from ...types.listen_v2model import ListenV2Model
from ...types.listen_v2sample_rate import ListenV2SampleRate
from ...types.listen_v2tag import ListenV2Tag
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: ListenV2Model,
        encoding: typing.Optional[ListenV2Encoding] = None,
        sample_rate: typing.Optional[ListenV2SampleRate] = None,
        eager_eot_threshold: typing.Optional[ListenV2EagerEotThreshold] = None,
        eot_threshold: typing.Optional[ListenV2EotThreshold] = None,
        eot_timeout_ms: typing.Optional[ListenV2EotTimeoutMs] = None,
        keyterm: typing.Optional[ListenV2KeytermParams] = None,
        mip_opt_out: typing.Optional[ListenV2MipOptOut] = None,
        tag: typing.Optional[ListenV2Tag] = 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 : ListenV2Model

        encoding : typing.Optional[ListenV2Encoding]

        sample_rate : typing.Optional[ListenV2SampleRate]

        eager_eot_threshold : typing.Optional[ListenV2EagerEotThreshold]

        eot_threshold : typing.Optional[ListenV2EotThreshold]

        eot_timeout_ms : typing.Optional[ListenV2EotTimeoutMs]

        keyterm : typing.Optional[ListenV2KeytermParams]

        mip_opt_out : typing.Optional[ListenV2MipOptOut]

        tag : typing.Optional[ListenV2Tag]

        authorization : typing.Optional[str]
            Use your API key or a [temporary token](/guides/fundamentals/token-based-authentication) for authentication via the `Authorization` header. In client-side environments where custom headers are not supported, use the [`Sec-WebSocket-Protocol`](/guides/deep-dives/using-the-sec-websocket-protocol) header instead.

            **Example:** `Authorization: Token %DEEPGRAM_API_KEY%` or `Authorization: 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"
        _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": convert_and_respect_annotation_metadata(
                            object_=convert_and_respect_annotation_metadata(
                                object_=keyterm, annotation=ListenV2KeytermParams, direction="write"
                            ),
                            annotation=ListenV2KeytermParams,
                            direction="write",
                        ),
                        "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._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 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 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: ListenV2Model,
        encoding: typing.Optional[ListenV2Encoding] = None,
        sample_rate: typing.Optional[ListenV2SampleRate] = None,
        eager_eot_threshold: typing.Optional[ListenV2EagerEotThreshold] = None,
        eot_threshold: typing.Optional[ListenV2EotThreshold] = None,
        eot_timeout_ms: typing.Optional[ListenV2EotTimeoutMs] = None,
        keyterm: typing.Optional[ListenV2KeytermParams] = None,
        mip_opt_out: typing.Optional[ListenV2MipOptOut] = None,
        tag: typing.Optional[ListenV2Tag] = 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 : ListenV2Model

        encoding : typing.Optional[ListenV2Encoding]

        sample_rate : typing.Optional[ListenV2SampleRate]

        eager_eot_threshold : typing.Optional[ListenV2EagerEotThreshold]

        eot_threshold : typing.Optional[ListenV2EotThreshold]

        eot_timeout_ms : typing.Optional[ListenV2EotTimeoutMs]

        keyterm : typing.Optional[ListenV2KeytermParams]

        mip_opt_out : typing.Optional[ListenV2MipOptOut]

        tag : typing.Optional[ListenV2Tag]

        authorization : typing.Optional[str]
            Use your API key or a [temporary token](/guides/fundamentals/token-based-authentication) for authentication via the `Authorization` header. In client-side environments where custom headers are not supported, use the [`Sec-WebSocket-Protocol`](/guides/deep-dives/using-the-sec-websocket-protocol) header instead.

            **Example:** `Authorization: Token %DEEPGRAM_API_KEY%` or `Authorization: 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"
        _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": convert_and_respect_annotation_metadata(
                            object_=convert_and_respect_annotation_metadata(
                                object_=keyterm, annotation=ListenV2KeytermParams, direction="write"
                            ),
                            annotation=ListenV2KeytermParams,
                            direction="write",
                        ),
                        "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._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 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.",
            )
