"""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
import httpx
import importlib
import sys
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Union, cast
from unkey.py import models, utils
from unkey.py._hooks import SDKHooks
from unkey.py.types import OptionalNullable, UNSET
import weakref

if TYPE_CHECKING:
    from unkey.py.analytics import Analytics
    from unkey.py.apis import Apis
    from unkey.py.identities import Identities
    from unkey.py.keys import Keys
    from unkey.py.permissions import Permissions
    from unkey.py.ratelimit import Ratelimit


class Unkey(BaseSDK):
    r"""Unkey API: Unkey's API provides programmatic access for all resources within our platform.


    ### Authentication
    #
    This API uses HTTP Bearer authentication with root keys. Most endpoints require specific permissions associated with your root key. When making requests, include your root key in the `Authorization` header:
    ```
    Authorization: Bearer unkey_xxxxxxxxxxx
    ```

    All responses follow a consistent envelope structure that separates operational metadata from actual data. This design provides several benefits:
    - Debugging: Every response includes a unique requestId for tracing issues
    - Consistency: Predictable response format across all endpoints
    - Extensibility: Easy to add new metadata without breaking existing integrations
    - Error Handling: Unified error format with actionable information

    ### Success Response Format:
    ```json
    {
    \"meta\": {
    \"requestId\": \"req_123456\"
    },
    \"data\": {
    // Actual response data here
    }
    }
    ```

    The meta object contains operational information:
    - `requestId`: Unique identifier for this request (essential for support)

    The data object contains the actual response data specific to each endpoint.

    ### Paginated Response Format:
    ```json
    {
    \"meta\": {
    \"requestId\": \"req_123456\"
    },
    \"data\": [
    // Array of results
    ],
    \"pagination\": {
    \"cursor\": \"next_page_token\",
    \"hasMore\": true
    }
    }
    ```

    The pagination object appears on list endpoints and contains:
    - `cursor`: Token for requesting the next page
    - `hasMore`: Whether more results are available

    ### Error Response Format:
    ```json
    {
    \"meta\": {
    \"requestId\": \"req_2c9a0jf23l4k567\"
    },
    \"error\": {
    \"detail\": \"The resource you are attempting to modify is protected and cannot be changed\",
    \"status\": 403,
    \"title\": \"Forbidden\",
    \"type\": \"https://unkey.com/docs/errors/unkey/application/protected_resource\"
    }
    }
    ```

    Error responses include comprehensive diagnostic information:
    - `title`: Human-readable error summary
    - `detail`: Specific description of what went wrong
    - `status`: HTTP status code
    - `type`: Link to error documentation
    - `errors`: Array of validation errors (for 400 responses)

    This structure ensures you always have the context needed to debug issues and take corrective action.
    """

    analytics: "Analytics"
    r"""Analytics query operations"""
    apis: "Apis"
    r"""API management operations"""
    identities: "Identities"
    r"""Identity management operations"""
    keys: "Keys"
    r"""API key management operations"""
    permissions: "Permissions"
    r"""Permission and role management operations"""
    ratelimit: "Ratelimit"
    r"""Rate limiting operations"""
    _sub_sdk_map = {
        "analytics": ("unkey.py.analytics", "Analytics"),
        "apis": ("unkey.py.apis", "Apis"),
        "identities": ("unkey.py.identities", "Identities"),
        "keys": ("unkey.py.keys", "Keys"),
        "permissions": ("unkey.py.permissions", "Permissions"),
        "ratelimit": ("unkey.py.ratelimit", "Ratelimit"),
    }

    def __init__(
        self,
        root_key: Optional[Union[Optional[str], Callable[[], 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 root_key: The root_key required for authentication
        :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(follow_redirects=True)
            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(follow_redirects=True)
            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(root_key):
            # pylint: disable=unnecessary-lambda-assignment
            security = lambda: models.Security(root_key=root_key())
        else:
            security = models.Security(root_key=root_key)

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

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

        hooks = SDKHooks()

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

        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

        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,
        )

    def dynamic_import(self, modname, retries=3):
        for attempt in range(retries):
            try:
                return importlib.import_module(modname)
            except KeyError:
                # Clear any half-initialized module and retry
                sys.modules.pop(modname, None)
                if attempt == retries - 1:
                    break
        raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")

    def __getattr__(self, name: str):
        if name in self._sub_sdk_map:
            module_path, class_name = self._sub_sdk_map[name]
            try:
                module = self.dynamic_import(module_path)
                klass = getattr(module, class_name)
                instance = klass(self.sdk_configuration, parent_ref=self)
                setattr(self, name, instance)
                return instance
            except ImportError as e:
                raise AttributeError(
                    f"Failed to import module {module_path} for attribute {name}: {e}"
                ) from e
            except AttributeError as e:
                raise AttributeError(
                    f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}"
                ) from e

        raise AttributeError(
            f"'{type(self).__name__}' object has no attribute '{name}'"
        )

    def __dir__(self):
        default_attrs = list(super().__dir__())
        lazy_attrs = list(self._sub_sdk_map.keys())
        return sorted(list(set(default_attrs + lazy_attrs)))

    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
