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

import typing
import urllib.parse
from contextlib import asynccontextmanager, contextmanager
from json.decoder import JSONDecodeError

import websockets.sync.client as websockets_sync_client
from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.pydantic_utilities import parse_obj_as
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 ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.control_plane_publish_event import ControlPlanePublishEvent
from ..types.http_validation_error import HttpValidationError
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 RawControlPlaneClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

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

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

        request : ControlPlanePublishEvent

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v0/evi/chat/{jsonable_encoder(chat_id)}/send",
            base_url=self._client_wrapper.get_environment().base,
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ControlPlanePublishEvent, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    @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._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._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 AsyncRawControlPlaneClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

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

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

        request : ControlPlanePublishEvent

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v0/evi/chat/{jsonable_encoder(chat_id)}/send",
            base_url=self._client_wrapper.get_environment().base,
            method="POST",
            json=convert_and_respect_annotation_metadata(
                object_=request, annotation=ControlPlanePublishEvent, direction="write"
            ),
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    @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._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._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.",
            )
