"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from .basesdk import BaseSDK
from .httpclient import AsyncHttpClient, ClientOwner, HttpClient, close_clients
from .sdkconfiguration import SDKConfiguration
from .utils.logger import Logger, get_default_logger
from .utils.retries import RetryConfig
from apideck_unify import models, utils
from apideck_unify._hooks import SDKHooks
from apideck_unify.accounting import Accounting
from apideck_unify.ats import Ats
from apideck_unify.connector_sdk import ConnectorSDK
from apideck_unify.crm import Crm
from apideck_unify.ecommerce import Ecommerce
from apideck_unify.filestorage import FileStorage
from apideck_unify.hris import Hris
from apideck_unify.issuetracking import IssueTracking
from apideck_unify.models import internal
from apideck_unify.sms import Sms
from apideck_unify.types import OptionalNullable, UNSET
from apideck_unify.vault import Vault
from apideck_unify.webhook_sdk import WebhookSDK
import httpx
from typing import Any, Callable, Dict, Optional, Union, cast
import weakref


class Apideck(BaseSDK):
    r"""Apideck: The Apideck OpenAPI Spec: SDK Optimized
    https://developers.apideck.com - Apideck Developer Docs
    """

    accounting: Accounting
    ats: Ats
    crm: Crm
    ecommerce: Ecommerce
    file_storage: FileStorage
    hris: Hris
    sms: Sms
    issue_tracking: IssueTracking
    connector: ConnectorSDK
    vault: Vault
    webhook: WebhookSDK

    def __init__(
        self,
        api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None,
        consumer_id: Optional[str] = None,
        app_id: Optional[str] = None,
        server_idx: Optional[int] = None,
        server_url: Optional[str] = None,
        url_params: Optional[Dict[str, str]] = None,
        client: Optional[HttpClient] = None,
        async_client: Optional[AsyncHttpClient] = None,
        retry_config: OptionalNullable[RetryConfig] = UNSET,
        timeout_ms: Optional[int] = None,
        debug_logger: Optional[Logger] = None,
    ) -> None:
        r"""Instantiates the SDK configuring it with the provided parameters.

        :param api_key: The api_key required for authentication
        :param consumer_id: Configures the consumer_id parameter for all supported operations
        :param app_id: Configures the app_id parameter for all supported operations
        :param server_idx: The index of the server to use for all methods
        :param server_url: The server URL to use for all methods
        :param url_params: Parameters to optionally template the server URL with
        :param client: The HTTP client to use for all synchronous methods
        :param async_client: The Async HTTP client to use for all asynchronous methods
        :param retry_config: The retry configuration to use for all supported methods
        :param timeout_ms: Optional request timeout applied to each operation in milliseconds
        """
        client_supplied = True
        if client is None:
            client = httpx.Client()
            client_supplied = False

        assert issubclass(
            type(client), HttpClient
        ), "The provided client must implement the HttpClient protocol."

        async_client_supplied = True
        if async_client is None:
            async_client = httpx.AsyncClient()
            async_client_supplied = False

        if debug_logger is None:
            debug_logger = get_default_logger()

        assert issubclass(
            type(async_client), AsyncHttpClient
        ), "The provided async_client must implement the AsyncHttpClient protocol."

        security: Any = None
        if callable(api_key):
            # pylint: disable=unnecessary-lambda-assignment
            security = lambda: models.Security(api_key=api_key())
        else:
            security = models.Security(api_key=api_key)

        if server_url is not None:
            if url_params is not None:
                server_url = utils.template_url(server_url, url_params)

        _globals = internal.Globals(
            consumer_id=utils.get_global_from_env(
                consumer_id, "APIDECK_CONSUMER_ID", str
            ),
            app_id=utils.get_global_from_env(app_id, "APIDECK_APP_ID", str),
        )

        BaseSDK.__init__(
            self,
            SDKConfiguration(
                client=client,
                client_supplied=client_supplied,
                async_client=async_client,
                async_client_supplied=async_client_supplied,
                globals=_globals,
                security=security,
                server_url=server_url,
                server_idx=server_idx,
                retry_config=retry_config,
                timeout_ms=timeout_ms,
                debug_logger=debug_logger,
            ),
        )

        hooks = SDKHooks()

        current_server_url, *_ = self.sdk_configuration.get_server_details()
        server_url, self.sdk_configuration.client = hooks.sdk_init(
            current_server_url, client
        )
        if current_server_url != server_url:
            self.sdk_configuration.server_url = server_url

        # pylint: disable=protected-access
        self.sdk_configuration.__dict__["_hooks"] = hooks

        weakref.finalize(
            self,
            close_clients,
            cast(ClientOwner, self.sdk_configuration),
            self.sdk_configuration.client,
            self.sdk_configuration.client_supplied,
            self.sdk_configuration.async_client,
            self.sdk_configuration.async_client_supplied,
        )

        self._init_sdks()

    def _init_sdks(self):
        self.accounting = Accounting(self.sdk_configuration)
        self.ats = Ats(self.sdk_configuration)
        self.crm = Crm(self.sdk_configuration)
        self.ecommerce = Ecommerce(self.sdk_configuration)
        self.file_storage = FileStorage(self.sdk_configuration)
        self.hris = Hris(self.sdk_configuration)
        self.sms = Sms(self.sdk_configuration)
        self.issue_tracking = IssueTracking(self.sdk_configuration)
        self.connector = ConnectorSDK(self.sdk_configuration)
        self.vault = Vault(self.sdk_configuration)
        self.webhook = WebhookSDK(self.sdk_configuration)

    def __enter__(self):
        return self

    async def __aenter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if (
            self.sdk_configuration.client is not None
            and not self.sdk_configuration.client_supplied
        ):
            self.sdk_configuration.client.close()
        self.sdk_configuration.client = None

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if (
            self.sdk_configuration.async_client is not None
            and not self.sdk_configuration.async_client_supplied
        ):
            await self.sdk_configuration.async_client.aclose()
        self.sdk_configuration.async_client = None
