"""Main SDK client classes."""

import os
from typing import Optional

from openai import AsyncOpenAI, OpenAI

from ._config import SDKConfig
from ._constants import (
    DEFAULT_BASE_URL,
    DEFAULT_MAX_RETRIES,
    DEFAULT_OPENROUTER_URL,
    DEFAULT_TIMEOUT,
    ENV_API_KEY,
    ENV_OPENROUTER_KEY,
)
from .tools.vision import AsyncVisionResource, VisionResource
from .tools.cdn import AsyncCDNResource, CDNResource
from .tools.shortlinks import AsyncShortlinksResource, ShortlinksResource
from .tools.keys import AsyncKeysResource, KeysResource
from .tools.cleaner import AsyncCleanerResource, CleanerResource
from .tools.models import AsyncModelsResource, ModelsResource


class SDKRouter(OpenAI):
    """
    Main SDK client - OpenAI-compatible with additional tools.

    Extends OpenAI client with vision, OCR, CDN, and shortlinks tools.

    Example:
        ```python
        from sdkrouter import SDKRouter

        client = SDKRouter(api_key="your-api-key")

        # OpenAI-compatible chat
        response = client.chat.completions.create(
            model="openai/gpt-4o",
            messages=[{"role": "user", "content": "Hello!"}],
        )

        # Vision analysis
        result = client.vision.analyze(image_url="https://example.com/image.jpg")

        # CDN upload
        file = client.cdn.upload(Path("image.png"))
        ```
    """

    def __init__(
        self,
        *,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        use_self_hosted: bool = True,
        openrouter_api_key: Optional[str] = None,
        timeout: float = DEFAULT_TIMEOUT,
        max_retries: int = DEFAULT_MAX_RETRIES,
        **kwargs,
    ):
        """
        Initialize SDKRouter client.

        Args:
            api_key: API key (or set SDKROUTER_API_KEY env var)
            base_url: Base URL for API (default: ai.sdkrouter.com)
            use_self_hosted: If True, use self-hosted proxy. If False, direct to OpenRouter
            openrouter_api_key: OpenRouter API key (for direct mode)
            timeout: Request timeout in seconds
            max_retries: Number of retries for failed requests
            **kwargs: Additional arguments passed to OpenAI client
        """
        # Resolve API key
        resolved_key = (
            api_key
            or os.getenv(ENV_API_KEY)
            or openrouter_api_key
            or os.getenv(ENV_OPENROUTER_KEY)
        )
        if not resolved_key:
            raise ValueError(
                "API key required. Set SDKROUTER_API_KEY environment variable "
                "or pass api_key= parameter."
            )

        # Resolve base URL
        if use_self_hosted:
            resolved_url = base_url or os.getenv("SDKROUTER_BASE_URL") or DEFAULT_BASE_URL
        else:
            resolved_url = DEFAULT_OPENROUTER_URL

        # Initialize OpenAI client
        super().__init__(
            api_key=resolved_key,
            base_url=resolved_url,
            timeout=timeout,
            max_retries=max_retries,
            **kwargs,
        )

        # Store configuration
        self._sdk_config = SDKConfig(
            api_key=resolved_key,
            base_url=resolved_url,
            use_self_hosted=use_self_hosted,
            timeout=timeout,
            max_retries=max_retries,
        )

        # Lazy-loaded tool resources
        self._vision: Optional[VisionResource] = None
        self._cdn: Optional[CDNResource] = None
        self._shortlinks: Optional[ShortlinksResource] = None
        self._keys: Optional[KeysResource] = None
        self._cleaner: Optional[CleanerResource] = None
        self._models: Optional[ModelsResource] = None

    @property
    def vision(self) -> VisionResource:
        """Vision analysis and OCR tool."""
        if self._vision is None:
            self._vision = VisionResource(self._sdk_config)
        return self._vision

    @property
    def cdn(self) -> CDNResource:
        """CDN file storage tool."""
        if self._cdn is None:
            self._cdn = CDNResource(self._sdk_config)
        return self._cdn

    @property
    def shortlinks(self) -> ShortlinksResource:
        """URL shortening tool."""
        if self._shortlinks is None:
            self._shortlinks = ShortlinksResource(self._sdk_config)
        return self._shortlinks

    @property
    def keys(self) -> KeysResource:
        """API keys management tool."""
        if self._keys is None:
            self._keys = KeysResource(self._sdk_config)
        return self._keys

    @property
    def cleaner(self) -> CleanerResource:
        """HTML cleaner tool."""
        if self._cleaner is None:
            self._cleaner = CleanerResource(self._sdk_config)
        return self._cleaner

    @property
    def models(self) -> ModelsResource:
        """LLM models listing tool."""
        if self._models is None:
            self._models = ModelsResource(self._sdk_config)
        return self._models

    @property
    def config(self) -> SDKConfig:
        """SDK configuration."""
        return self._sdk_config


class AsyncSDKRouter(AsyncOpenAI):
    """
    Async SDK client - OpenAI-compatible with additional tools.

    Async version of SDKRouter for use in async contexts.

    Example:
        ```python
        from sdkrouter import AsyncSDKRouter

        client = AsyncSDKRouter(api_key="your-api-key")

        # Async chat
        response = await client.chat.completions.create(
            model="openai/gpt-4o",
            messages=[{"role": "user", "content": "Hello!"}],
        )

        # Async vision
        result = await client.vision.analyze(image_url="https://example.com/image.jpg")
        ```
    """

    def __init__(
        self,
        *,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        use_self_hosted: bool = True,
        openrouter_api_key: Optional[str] = None,
        timeout: float = DEFAULT_TIMEOUT,
        max_retries: int = DEFAULT_MAX_RETRIES,
        **kwargs,
    ):
        """Initialize async SDKRouter client."""
        # Resolve API key
        resolved_key = (
            api_key
            or os.getenv(ENV_API_KEY)
            or openrouter_api_key
            or os.getenv(ENV_OPENROUTER_KEY)
        )
        if not resolved_key:
            raise ValueError(
                "API key required. Set SDKROUTER_API_KEY environment variable "
                "or pass api_key= parameter."
            )

        # Resolve base URL
        if use_self_hosted:
            resolved_url = base_url or os.getenv("SDKROUTER_BASE_URL") or DEFAULT_BASE_URL
        else:
            resolved_url = DEFAULT_OPENROUTER_URL

        # Initialize AsyncOpenAI client
        super().__init__(
            api_key=resolved_key,
            base_url=resolved_url,
            timeout=timeout,
            max_retries=max_retries,
            **kwargs,
        )

        # Store configuration
        self._sdk_config = SDKConfig(
            api_key=resolved_key,
            base_url=resolved_url,
            use_self_hosted=use_self_hosted,
            timeout=timeout,
            max_retries=max_retries,
        )

        # Lazy-loaded async tool resources
        self._vision: Optional[AsyncVisionResource] = None
        self._cdn: Optional[AsyncCDNResource] = None
        self._shortlinks: Optional[AsyncShortlinksResource] = None
        self._keys: Optional[AsyncKeysResource] = None
        self._cleaner: Optional[AsyncCleanerResource] = None
        self._models: Optional[AsyncModelsResource] = None

    @property
    def vision(self) -> AsyncVisionResource:
        """Vision analysis and OCR tool (async)."""
        if self._vision is None:
            self._vision = AsyncVisionResource(self._sdk_config)
        return self._vision

    @property
    def cdn(self) -> AsyncCDNResource:
        """CDN file storage tool (async)."""
        if self._cdn is None:
            self._cdn = AsyncCDNResource(self._sdk_config)
        return self._cdn

    @property
    def shortlinks(self) -> AsyncShortlinksResource:
        """URL shortening tool (async)."""
        if self._shortlinks is None:
            self._shortlinks = AsyncShortlinksResource(self._sdk_config)
        return self._shortlinks

    @property
    def keys(self) -> AsyncKeysResource:
        """API keys management tool (async)."""
        if self._keys is None:
            self._keys = AsyncKeysResource(self._sdk_config)
        return self._keys

    @property
    def cleaner(self) -> AsyncCleanerResource:
        """HTML cleaner tool (async)."""
        if self._cleaner is None:
            self._cleaner = AsyncCleanerResource(self._sdk_config)
        return self._cleaner

    @property
    def models(self) -> AsyncModelsResource:
        """LLM models listing tool (async)."""
        if self._models is None:
            self._models = AsyncModelsResource(self._sdk_config)
        return self._models

    @property
    def config(self) -> SDKConfig:
        """SDK configuration."""
        return self._sdk_config
