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

if TYPE_CHECKING:
    from openrouter.analytics import Analytics
    from openrouter.api_keys import APIKeys
    from openrouter.benchmarks import Benchmarks
    from openrouter.beta import Beta
    from openrouter.byok import Byok
    from openrouter.chat import Chat
    from openrouter.credits import Credits
    from openrouter.datasets import Datasets
    from openrouter.embeddings import Embeddings
    from openrouter.endpoints import Endpoints
    from openrouter.files import Files
    from openrouter.generations import Generations
    from openrouter.guardrails import Guardrails
    from openrouter.models_ import Models
    from openrouter.oauth import OAuth
    from openrouter.observability import Observability
    from openrouter.organization import Organization
    from openrouter.presets import Presets
    from openrouter.providers import Providers
    from openrouter.rerank import Rerank
    from openrouter.stt import Stt
    from openrouter.tts import Tts
    from openrouter.video_generation import VideoGeneration
    from openrouter.workspaces import Workspaces


class OpenRouter(BaseSDK):
    r"""OpenRouter API: OpenAI-compatible API with additional OpenRouter features
    https://openrouter.ai/docs - OpenRouter Documentation
    """

    analytics: "Analytics"
    r"""Analytics and usage endpoints"""
    beta: "Beta"
    tts: "Tts"
    r"""Text-to-speech endpoints"""
    stt: "Stt"
    r"""Speech-to-text endpoints"""
    o_auth: "OAuth"
    r"""OAuth authentication endpoints"""
    benchmarks: "Benchmarks"
    r"""Benchmarks endpoints"""
    byok: "Byok"
    r"""BYOK endpoints"""
    chat: "Chat"
    credits: "Credits"
    r"""Credit management endpoints"""
    datasets: "Datasets"
    r"""Datasets endpoints"""
    embeddings: "Embeddings"
    r"""Text embedding endpoints"""
    endpoints: "Endpoints"
    r"""Endpoint information"""
    files: "Files"
    r"""Files endpoints"""
    generations: "Generations"
    r"""Generation history endpoints"""
    guardrails: "Guardrails"
    r"""Guardrails endpoints"""
    api_keys: "APIKeys"
    r"""API key management endpoints"""
    models: "Models"
    r"""Model information endpoints"""
    observability: "Observability"
    r"""Observability endpoints"""
    organization: "Organization"
    r"""Organization endpoints"""
    presets: "Presets"
    r"""Presets endpoints"""
    providers: "Providers"
    r"""Provider information endpoints"""
    rerank: "Rerank"
    r"""Rerank endpoints"""
    video_generation: "VideoGeneration"
    r"""Video Generation endpoints"""
    workspaces: "Workspaces"
    r"""Workspaces endpoints"""
    _sub_sdk_map = {
        "analytics": ("openrouter.analytics", "Analytics"),
        "beta": ("openrouter.beta", "Beta"),
        "tts": ("openrouter.tts", "Tts"),
        "stt": ("openrouter.stt", "Stt"),
        "o_auth": ("openrouter.oauth", "OAuth"),
        "benchmarks": ("openrouter.benchmarks", "Benchmarks"),
        "byok": ("openrouter.byok", "Byok"),
        "chat": ("openrouter.chat", "Chat"),
        "credits": ("openrouter.credits", "Credits"),
        "datasets": ("openrouter.datasets", "Datasets"),
        "embeddings": ("openrouter.embeddings", "Embeddings"),
        "endpoints": ("openrouter.endpoints", "Endpoints"),
        "files": ("openrouter.files", "Files"),
        "generations": ("openrouter.generations", "Generations"),
        "guardrails": ("openrouter.guardrails", "Guardrails"),
        "api_keys": ("openrouter.api_keys", "APIKeys"),
        "models": ("openrouter.models_", "Models"),
        "observability": ("openrouter.observability", "Observability"),
        "organization": ("openrouter.organization", "Organization"),
        "presets": ("openrouter.presets", "Presets"),
        "providers": ("openrouter.providers", "Providers"),
        "rerank": ("openrouter.rerank", "Rerank"),
        "video_generation": ("openrouter.video_generation", "VideoGeneration"),
        "workspaces": ("openrouter.workspaces", "Workspaces"),
    }

    def __init__(
        self,
        api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None,
        http_referer: Optional[str] = None,
        x_open_router_title: Optional[str] = None,
        x_open_router_categories: Optional[str] = None,
        server: Optional[str] = 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 http_referer: Configures the http_referer parameter for all supported operations
        :param x_open_router_title: Configures the x_open_router_title parameter for all supported operations
        :param x_open_router_categories: Configures the x_open_router_categories parameter for all supported operations
        :param server: The server by name 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(api_key):
            # pylint: disable=unnecessary-lambda-assignment
            security = lambda: components.Security(api_key=api_key())
        else:
            security = components.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(
            http_referer=utils.get_global_from_env(
                http_referer, "OPENROUTER_HTTP_REFERER", str
            ),
            x_open_router_title=utils.get_global_from_env(
                x_open_router_title, "OPENROUTER_X_OPEN_ROUTER_TITLE", str
            ),
            x_open_router_categories=utils.get_global_from_env(
                x_open_router_categories, "OPENROUTER_X_OPEN_ROUTER_CATEGORIES", 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=server,
                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

        self.sdk_configuration = hooks.sdk_init(self.sdk_configuration)

        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
