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

import os
import typing
import urllib.parse
from json.decoder import JSONDecodeError

import httpx

from .batches.client import AsyncBatchesClient, BatchesClient
from .calls.client import AsyncCallsClient, CallsClient
from .commons.errors.server_error import ServerError
from .commons.errors.unauthorized_error import UnauthorizedError
from .commons.types.error_body import ErrorBody
from .core.api_error import ApiError
from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from .core.jsonable_encoder import jsonable_encoder
from .core.remove_none_from_dict import remove_none_from_dict
from .core.request_options import RequestOptions
from .environment import BlandAIEnvironment
from .inbound_numbers.client import AsyncInboundNumbersClient, InboundNumbersClient
from .outbound_numbers.client import AsyncOutboundNumbersClient, OutboundNumbersClient
from .sms.client import AsyncSmsClient, SmsClient
from .types.send_call import SendCall
from .types.send_call_response import SendCallResponse
from .voices.client import AsyncVoicesClient, VoicesClient

try:
    import pydantic.v1 as pydantic  # type: ignore
except ImportError:
    import pydantic  # type: ignore

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


class BlandAI:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propogate to these functions.

    Parameters:
        - base_url: typing.Optional[str]. The base url to use for requests from the client.

        - environment: BlandAIEnvironment. The environment to use for requests from the client. from .environment import BlandAIEnvironment

                                           Defaults to BlandAIEnvironment.PRODUCTION

        - api_key: typing.Optional[str].

        - timeout: typing.Optional[float]. The timeout to be used, in seconds, for requests by default the timeout is 60 seconds.

        - httpx_client: typing.Optional[httpx.Client]. The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
    ---
    from blandai.client import BlandAI

    client = BlandAI(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: BlandAIEnvironment = BlandAIEnvironment.PRODUCTION,
        api_key: typing.Optional[str] = os.getenv("BLAND_API_KEY"),
        timeout: typing.Optional[float] = 60,
        httpx_client: typing.Optional[httpx.Client] = None,
    ):
        if api_key is None:
            raise ApiError(body="The client must be instantiated be either passing in api_key or setting BLAND_API_KEY")
        self._client_wrapper = SyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx.Client(timeout=timeout) if httpx_client is None else httpx_client,
        )
        self.batches = BatchesClient(client_wrapper=self._client_wrapper)
        self.calls = CallsClient(client_wrapper=self._client_wrapper)
        self.inbound_numbers = InboundNumbersClient(client_wrapper=self._client_wrapper)
        self.outbound_numbers = OutboundNumbersClient(client_wrapper=self._client_wrapper)
        self.sms = SmsClient(client_wrapper=self._client_wrapper)
        self.voices = VoicesClient(client_wrapper=self._client_wrapper)

    def call(self, *, request: SendCall, request_options: typing.Optional[RequestOptions] = None) -> SendCallResponse:
        """
        Send an AI phone call with a custom objective and actions.

        Parameters:
            - request: SendCall.

            - request_options: typing.Optional[RequestOptions]. Request-specific configuration.
        ---
        from blandai import PronunciationObject, SendCall
        from blandai.client import BlandAI

        client = BlandAI(
            api_key="YOUR_API_KEY",
        )
        client.call(
            request=SendCall(
                phone_number="29382721828",
                task="Would love for you to check out our AI API!",
                temperature=0.5,
                transfer_list={
                    "default": "+1234567890",
                    "sales": "+1234567890",
                    "support": "+1234567890",
                    "billing": "+1234567890",
                },
                model="enhanced",
                pronunciation_guide=[
                    PronunciationObject(
                        word="API",
                        pronunciation="A P I",
                    ),
                    PronunciationObject(
                        word="AI",
                        pronunciation="A I",
                    ),
                ],
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "v1/calls"),
            params=jsonable_encoder(
                request_options.get("additional_query_parameters") if request_options is not None else None
            ),
            json=jsonable_encoder(request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else 60,
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(SendCallResponse, _response.json())  # type: ignore
        if _response.status_code == 500:
            raise ServerError(pydantic.parse_obj_as(ErrorBody, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic.parse_obj_as(ErrorBody, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncBlandAI:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propogate to these functions.

    Parameters:
        - base_url: typing.Optional[str]. The base url to use for requests from the client.

        - environment: BlandAIEnvironment. The environment to use for requests from the client. from .environment import BlandAIEnvironment

                                           Defaults to BlandAIEnvironment.PRODUCTION

        - api_key: typing.Optional[str].

        - timeout: typing.Optional[float]. The timeout to be used, in seconds, for requests by default the timeout is 60 seconds.

        - httpx_client: typing.Optional[httpx.AsyncClient]. The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
    ---
    from blandai.client import AsyncBlandAI

    client = AsyncBlandAI(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: BlandAIEnvironment = BlandAIEnvironment.PRODUCTION,
        api_key: typing.Optional[str] = os.getenv("BLAND_API_KEY"),
        timeout: typing.Optional[float] = 60,
        httpx_client: typing.Optional[httpx.AsyncClient] = None,
    ):
        if api_key is None:
            raise ApiError(body="The client must be instantiated be either passing in api_key or setting BLAND_API_KEY")
        self._client_wrapper = AsyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx.AsyncClient(timeout=timeout) if httpx_client is None else httpx_client,
        )
        self.batches = AsyncBatchesClient(client_wrapper=self._client_wrapper)
        self.calls = AsyncCallsClient(client_wrapper=self._client_wrapper)
        self.inbound_numbers = AsyncInboundNumbersClient(client_wrapper=self._client_wrapper)
        self.outbound_numbers = AsyncOutboundNumbersClient(client_wrapper=self._client_wrapper)
        self.sms = AsyncSmsClient(client_wrapper=self._client_wrapper)
        self.voices = AsyncVoicesClient(client_wrapper=self._client_wrapper)

    async def call(
        self, *, request: SendCall, request_options: typing.Optional[RequestOptions] = None
    ) -> SendCallResponse:
        """
        Send an AI phone call with a custom objective and actions.

        Parameters:
            - request: SendCall.

            - request_options: typing.Optional[RequestOptions]. Request-specific configuration.
        ---
        from blandai import PronunciationObject, SendCall
        from blandai.client import AsyncBlandAI

        client = AsyncBlandAI(
            api_key="YOUR_API_KEY",
        )
        await client.call(
            request=SendCall(
                phone_number="29382721828",
                task="Would love for you to check out our AI API!",
                temperature=0.5,
                transfer_list={
                    "default": "+1234567890",
                    "sales": "+1234567890",
                    "support": "+1234567890",
                    "billing": "+1234567890",
                },
                model="enhanced",
                pronunciation_guide=[
                    PronunciationObject(
                        word="API",
                        pronunciation="A P I",
                    ),
                    PronunciationObject(
                        word="AI",
                        pronunciation="A I",
                    ),
                ],
            ),
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "POST",
            urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "v1/calls"),
            params=jsonable_encoder(
                request_options.get("additional_query_parameters") if request_options is not None else None
            ),
            json=jsonable_encoder(request)
            if request_options is None or request_options.get("additional_body_parameters") is None
            else {
                **jsonable_encoder(request),
                **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))),
            },
            headers=jsonable_encoder(
                remove_none_from_dict(
                    {
                        **self._client_wrapper.get_headers(),
                        **(request_options.get("additional_headers", {}) if request_options is not None else {}),
                    }
                )
            ),
            timeout=request_options.get("timeout_in_seconds")
            if request_options is not None and request_options.get("timeout_in_seconds") is not None
            else 60,
            retries=0,
            max_retries=request_options.get("max_retries") if request_options is not None else 0,  # type: ignore
        )
        if 200 <= _response.status_code < 300:
            return pydantic.parse_obj_as(SendCallResponse, _response.json())  # type: ignore
        if _response.status_code == 500:
            raise ServerError(pydantic.parse_obj_as(ErrorBody, _response.json()))  # type: ignore
        if _response.status_code == 401:
            raise UnauthorizedError(pydantic.parse_obj_as(ErrorBody, _response.json()))  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


def _get_base_url(*, base_url: typing.Optional[str] = None, environment: BlandAIEnvironment) -> str:
    if base_url is not None:
        return base_url
    elif environment is not None:
        return environment.value
    else:
        raise Exception("Please pass in either base_url or environment to construct the client")
