# 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 ..types.control_plane_publish_event import ControlPlanePublishEvent
from .raw_client import AsyncRawControlPlaneClient, RawControlPlaneClient
from .socket_client import AsyncControlPlaneSocketClient, ControlPlaneSocketClient

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

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class ControlPlaneClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawControlPlaneClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawControlPlaneClient
        """
        return self._raw_client

    def send(
        self,
        chat_id: str,
        *,
        request: ControlPlanePublishEvent,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Send a message to a specific chat.

        Parameters
        ----------
        chat_id : str

        request : ControlPlanePublishEvent

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

        Returns
        -------
        None

        Examples
        --------
        from hume import HumeClient
        from hume.empathic_voice import SessionSettings

        client = HumeClient(
            api_key="YOUR_API_KEY",
        )
        client.empathic_voice.control_plane.send(
            chat_id="chat_id",
            request=SessionSettings(),
        )
        """
        _response = self._raw_client.send(chat_id, request=request, request_options=request_options)
        return _response.data

    @contextmanager
    def connect(
        self,
        chat_id: str,
        *,
        access_token: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[ControlPlaneSocketClient]:
        """
        Connects to an in-progress EVI chat session. The original chat must have been started with `allow_connection=true`. The connection can be used to send and receive the same messages as the original chat, with the exception that `audio_input` messages are not allowed.

        Parameters
        ----------
        chat_id : str
            The ID of the chat to connect to.

        access_token : typing.Optional[str]
            Access token used for authenticating the client. If not provided, an `api_key` must be provided to authenticate.

            The access token is generated using both an API key and a Secret key, which provides an additional layer of security compared to using just an API key.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

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

        Returns
        -------
        ControlPlaneSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().evi + "/chat/"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "access_token": access_token,
                        **(
                            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 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 ControlPlaneSocketClient(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 AsyncControlPlaneClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawControlPlaneClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawControlPlaneClient
        """
        return self._raw_client

    async def send(
        self,
        chat_id: str,
        *,
        request: ControlPlanePublishEvent,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Send a message to a specific chat.

        Parameters
        ----------
        chat_id : str

        request : ControlPlanePublishEvent

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from hume import AsyncHumeClient
        from hume.empathic_voice import SessionSettings

        client = AsyncHumeClient(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.empathic_voice.control_plane.send(
                chat_id="chat_id",
                request=SessionSettings(),
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.send(chat_id, request=request, request_options=request_options)
        return _response.data

    @asynccontextmanager
    async def connect(
        self,
        chat_id: str,
        *,
        access_token: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncControlPlaneSocketClient]:
        """
        Connects to an in-progress EVI chat session. The original chat must have been started with `allow_connection=true`. The connection can be used to send and receive the same messages as the original chat, with the exception that `audio_input` messages are not allowed.

        Parameters
        ----------
        chat_id : str
            The ID of the chat to connect to.

        access_token : typing.Optional[str]
            Access token used for authenticating the client. If not provided, an `api_key` must be provided to authenticate.

            The access token is generated using both an API key and a Secret key, which provides an additional layer of security compared to using just an API key.

            For more details, refer to the [Authentication Strategies Guide](/docs/introduction/api-key#authentication-strategies).

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

        Returns
        -------
        AsyncControlPlaneSocketClient
        """
        ws_url = self._raw_client._client_wrapper.get_environment().evi + "/chat/"
        _encoded_query_params = encode_query(
            jsonable_encoder(
                remove_none_from_dict(
                    {
                        "access_token": access_token,
                        **(
                            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 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 AsyncControlPlaneSocketClient(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.",
            )
