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

from __future__ import annotations

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 .raw_client import AsyncRawV1Client, RawV1Client
from .socket_client import AsyncV1SocketClient, V1SocketClient

if typing.TYPE_CHECKING:
    from .media.client import AsyncMediaClient, MediaClient

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 V1Client:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawV1Client(client_wrapper=client_wrapper)
        self._client_wrapper = client_wrapper
        self._media: typing.Optional[MediaClient] = None

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

        Returns
        -------
        RawV1Client
        """
        return self._raw_client

    @contextmanager
    def connect(
        self,
        *,
        callback: typing.Optional[str] = None,
        callback_method: typing.Optional[str] = None,
        channels: typing.Optional[str] = None,
        detect_entities: typing.Optional[str] = None,
        diarize: typing.Optional[str] = None,
        dictation: typing.Optional[str] = None,
        encoding: typing.Optional[str] = None,
        endpointing: typing.Optional[str] = None,
        extra: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        interim_results: typing.Optional[str] = None,
        keyterm: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        keywords: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        language: typing.Optional[str] = None,
        mip_opt_out: typing.Optional[str] = None,
        model: str,
        multichannel: typing.Optional[str] = None,
        numerals: typing.Optional[str] = None,
        profanity_filter: typing.Optional[str] = None,
        punctuate: typing.Optional[str] = None,
        redact: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        replace: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        sample_rate: typing.Optional[str] = None,
        search: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        smart_format: typing.Optional[str] = None,
        tag: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        utterance_end_ms: typing.Optional[str] = None,
        vad_events: typing.Optional[str] = None,
        version: typing.Optional[str] = None,
        authorization: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[V1SocketClient]:
        """
        Transcribe audio and video using Deepgram's speech-to-text WebSocket

        Parameters
        ----------
        callback : typing.Optional[str]

        callback_method : typing.Optional[str]

        channels : typing.Optional[str]

        detect_entities : typing.Optional[str]

        diarize : typing.Optional[str]

        dictation : typing.Optional[str]

        encoding : typing.Optional[str]

        endpointing : typing.Optional[str]

        extra : typing.Optional[str]

        interim_results : typing.Optional[str]

        keyterm : typing.Optional[str]

        keywords : typing.Optional[str]

        language : typing.Optional[str]

        mip_opt_out : typing.Optional[str]

        model : str
            AI model to use for the transcription

        multichannel : typing.Optional[str]

        numerals : typing.Optional[str]

        profanity_filter : typing.Optional[str]

        punctuate : typing.Optional[str]

        redact : typing.Optional[str]

        replace : typing.Optional[str]

        sample_rate : typing.Optional[str]

        search : typing.Optional[str]

        smart_format : typing.Optional[str]

        tag : typing.Optional[str]

        utterance_end_ms : typing.Optional[str]

        vad_events : typing.Optional[str]

        version : 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
        -------
        V1SocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().production + "/v1/listen"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "callback": callback,
                        "callback_method": callback_method,
                        "channels": channels,
                        "detect_entities": detect_entities,
                        "diarize": diarize,
                        "dictation": dictation,
                        "encoding": encoding,
                        "endpointing": endpointing,
                        "extra": extra,
                        "interim_results": interim_results,
                        "keyterm": keyterm,
                        "keywords": keywords,
                        "language": language,
                        "mip_opt_out": mip_opt_out,
                        "model": model,
                        "multichannel": multichannel,
                        "numerals": numerals,
                        "profanity_filter": profanity_filter,
                        "punctuate": punctuate,
                        "redact": redact,
                        "replace": replace,
                        "sample_rate": sample_rate,
                        "search": search,
                        "smart_format": smart_format,
                        "tag": tag,
                        "utterance_end_ms": utterance_end_ms,
                        "vad_events": vad_events,
                        "version": version,
                        **(
                            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 V1SocketClient(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.",
            )

    @property
    def media(self):
        if self._media is None:
            from .media.client import MediaClient  # noqa: E402

            self._media = MediaClient(client_wrapper=self._client_wrapper)
        return self._media


class AsyncV1Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawV1Client(client_wrapper=client_wrapper)
        self._client_wrapper = client_wrapper
        self._media: typing.Optional[AsyncMediaClient] = None

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

        Returns
        -------
        AsyncRawV1Client
        """
        return self._raw_client

    @asynccontextmanager
    async def connect(
        self,
        *,
        callback: typing.Optional[str] = None,
        callback_method: typing.Optional[str] = None,
        channels: typing.Optional[str] = None,
        detect_entities: typing.Optional[str] = None,
        diarize: typing.Optional[str] = None,
        dictation: typing.Optional[str] = None,
        encoding: typing.Optional[str] = None,
        endpointing: typing.Optional[str] = None,
        extra: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        interim_results: typing.Optional[str] = None,
        keyterm: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        keywords: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        language: typing.Optional[str] = None,
        mip_opt_out: typing.Optional[str] = None,
        model: str,
        multichannel: typing.Optional[str] = None,
        numerals: typing.Optional[str] = None,
        profanity_filter: typing.Optional[str] = None,
        punctuate: typing.Optional[str] = None,
        redact: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        replace: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        sample_rate: typing.Optional[str] = None,
        search: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        smart_format: typing.Optional[str] = None,
        tag: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        utterance_end_ms: typing.Optional[str] = None,
        vad_events: typing.Optional[str] = None,
        version: typing.Optional[str] = None,
        authorization: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncV1SocketClient]:
        """
        Transcribe audio and video using Deepgram's speech-to-text WebSocket

        Parameters
        ----------
        callback : typing.Optional[str]

        callback_method : typing.Optional[str]

        channels : typing.Optional[str]

        detect_entities : typing.Optional[str]

        diarize : typing.Optional[str]

        dictation : typing.Optional[str]

        encoding : typing.Optional[str]

        endpointing : typing.Optional[str]

        extra : typing.Optional[str]

        interim_results : typing.Optional[str]

        keyterm : typing.Optional[str]

        keywords : typing.Optional[str]

        language : typing.Optional[str]

        mip_opt_out : typing.Optional[str]

        model : str
            AI model to use for the transcription

        multichannel : typing.Optional[str]

        numerals : typing.Optional[str]

        profanity_filter : typing.Optional[str]

        punctuate : typing.Optional[str]

        redact : typing.Optional[str]

        replace : typing.Optional[str]

        sample_rate : typing.Optional[str]

        search : typing.Optional[str]

        smart_format : typing.Optional[str]

        tag : typing.Optional[str]

        utterance_end_ms : typing.Optional[str]

        vad_events : typing.Optional[str]

        version : 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
        -------
        AsyncV1SocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().production + "/v1/listen"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "callback": callback,
                        "callback_method": callback_method,
                        "channels": channels,
                        "detect_entities": detect_entities,
                        "diarize": diarize,
                        "dictation": dictation,
                        "encoding": encoding,
                        "endpointing": endpointing,
                        "extra": extra,
                        "interim_results": interim_results,
                        "keyterm": keyterm,
                        "keywords": keywords,
                        "language": language,
                        "mip_opt_out": mip_opt_out,
                        "model": model,
                        "multichannel": multichannel,
                        "numerals": numerals,
                        "profanity_filter": profanity_filter,
                        "punctuate": punctuate,
                        "redact": redact,
                        "replace": replace,
                        "sample_rate": sample_rate,
                        "search": search,
                        "smart_format": smart_format,
                        "tag": tag,
                        "utterance_end_ms": utterance_end_ms,
                        "vad_events": vad_events,
                        "version": version,
                        **(
                            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 AsyncV1SocketClient(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.",
            )

    @property
    def media(self):
        if self._media is None:
            from .media.client import AsyncMediaClient  # noqa: E402

            self._media = AsyncMediaClient(client_wrapper=self._client_wrapper)
        return self._media
