# 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 .socket_client import AsyncV1SocketClient, V1SocketClient

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

    @contextmanager
    def connect(
        self,
        *,
        callback: typing.Optional[str] = None,
        callback_method: typing.Optional[str] = None,
        channels: 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[str] = None,
        interim_results: typing.Optional[str] = None,
        keyterm: typing.Optional[str] = None,
        keywords: typing.Optional[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[str] = None,
        replace: typing.Optional[str] = None,
        sample_rate: typing.Optional[str] = None,
        search: typing.Optional[str] = None,
        smart_format: typing.Optional[str] = None,
        tag: typing.Optional[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]

        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._client_wrapper.get_environment().production + "/v1/listen"
        query_params = httpx.QueryParams()
        if callback is not None:
            query_params = query_params.add("callback", callback)
        if callback_method is not None:
            query_params = query_params.add("callback_method", callback_method)
        if channels is not None:
            query_params = query_params.add("channels", channels)
        if diarize is not None:
            query_params = query_params.add("diarize", diarize)
        if dictation is not None:
            query_params = query_params.add("dictation", dictation)
        if encoding is not None:
            query_params = query_params.add("encoding", encoding)
        if endpointing is not None:
            query_params = query_params.add("endpointing", endpointing)
        if extra is not None:
            query_params = query_params.add("extra", extra)
        if interim_results is not None:
            query_params = query_params.add("interim_results", interim_results)
        if keyterm is not None:
            query_params = query_params.add("keyterm", keyterm)
        if keywords is not None:
            query_params = query_params.add("keywords", keywords)
        if language is not None:
            query_params = query_params.add("language", language)
        if mip_opt_out is not None:
            query_params = query_params.add("mip_opt_out", mip_opt_out)
        if model is not None:
            query_params = query_params.add("model", model)
        if multichannel is not None:
            query_params = query_params.add("multichannel", multichannel)
        if numerals is not None:
            query_params = query_params.add("numerals", numerals)
        if profanity_filter is not None:
            query_params = query_params.add("profanity_filter", profanity_filter)
        if punctuate is not None:
            query_params = query_params.add("punctuate", punctuate)
        if redact is not None:
            query_params = query_params.add("redact", redact)
        if replace is not None:
            query_params = query_params.add("replace", replace)
        if sample_rate is not None:
            query_params = query_params.add("sample_rate", sample_rate)
        if search is not None:
            query_params = query_params.add("search", search)
        if smart_format is not None:
            query_params = query_params.add("smart_format", smart_format)
        if tag is not None:
            query_params = query_params.add("tag", tag)
        if utterance_end_ms is not None:
            query_params = query_params.add("utterance_end_ms", utterance_end_ms)
        if vad_events is not None:
            query_params = query_params.add("vad_events", vad_events)
        if version is not None:
            query_params = query_params.add("version", version)
        ws_url = ws_url + f"?{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 V1SocketClient(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 AsyncRawV1Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @asynccontextmanager
    async def connect(
        self,
        *,
        callback: typing.Optional[str] = None,
        callback_method: typing.Optional[str] = None,
        channels: 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[str] = None,
        interim_results: typing.Optional[str] = None,
        keyterm: typing.Optional[str] = None,
        keywords: typing.Optional[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[str] = None,
        replace: typing.Optional[str] = None,
        sample_rate: typing.Optional[str] = None,
        search: typing.Optional[str] = None,
        smart_format: typing.Optional[str] = None,
        tag: typing.Optional[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]

        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._client_wrapper.get_environment().production + "/v1/listen"
        query_params = httpx.QueryParams()
        if callback is not None:
            query_params = query_params.add("callback", callback)
        if callback_method is not None:
            query_params = query_params.add("callback_method", callback_method)
        if channels is not None:
            query_params = query_params.add("channels", channels)
        if diarize is not None:
            query_params = query_params.add("diarize", diarize)
        if dictation is not None:
            query_params = query_params.add("dictation", dictation)
        if encoding is not None:
            query_params = query_params.add("encoding", encoding)
        if endpointing is not None:
            query_params = query_params.add("endpointing", endpointing)
        if extra is not None:
            query_params = query_params.add("extra", extra)
        if interim_results is not None:
            query_params = query_params.add("interim_results", interim_results)
        if keyterm is not None:
            query_params = query_params.add("keyterm", keyterm)
        if keywords is not None:
            query_params = query_params.add("keywords", keywords)
        if language is not None:
            query_params = query_params.add("language", language)
        if mip_opt_out is not None:
            query_params = query_params.add("mip_opt_out", mip_opt_out)
        if model is not None:
            query_params = query_params.add("model", model)
        if multichannel is not None:
            query_params = query_params.add("multichannel", multichannel)
        if numerals is not None:
            query_params = query_params.add("numerals", numerals)
        if profanity_filter is not None:
            query_params = query_params.add("profanity_filter", profanity_filter)
        if punctuate is not None:
            query_params = query_params.add("punctuate", punctuate)
        if redact is not None:
            query_params = query_params.add("redact", redact)
        if replace is not None:
            query_params = query_params.add("replace", replace)
        if sample_rate is not None:
            query_params = query_params.add("sample_rate", sample_rate)
        if search is not None:
            query_params = query_params.add("search", search)
        if smart_format is not None:
            query_params = query_params.add("smart_format", smart_format)
        if tag is not None:
            query_params = query_params.add("tag", tag)
        if utterance_end_ms is not None:
            query_params = query_params.add("utterance_end_ms", utterance_end_ms)
        if vad_events is not None:
            query_params = query_params.add("vad_events", vad_events)
        if version is not None:
            query_params = query_params.add("version", version)
        ws_url = ws_url + f"?{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 AsyncV1SocketClient(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.",
            )
