from __future__ import annotations

import os
from dataclasses import dataclass

from openpoker.types import AIProvider

try:
    from anthropic import AsyncAnthropic
except ModuleNotFoundError:
    AsyncAnthropic = None

try:
    from openai import AsyncOpenAI
except ModuleNotFoundError:
    AsyncOpenAI = None


@dataclass
class ProviderClients:
    async_openai_client: AsyncOpenAI | None
    async_anthropic_client: AsyncAnthropic | None
    async_openrouter_client: AsyncOpenAI | None

    @classmethod
    def from_environment(cls) -> ProviderClients:
        openai_key = os.getenv("OPENAI_API_KEY")
        anthropic_key = os.getenv("ANTHROPIC_API_KEY")
        openrouter_key = os.getenv("OPENROUTER_API_KEY")

        openai_client = AsyncOpenAI(api_key=openai_key) if AsyncOpenAI is not None and openai_key else None
        anthropic_client = (
            AsyncAnthropic(api_key=anthropic_key) if AsyncAnthropic is not None and anthropic_key else None
        )
        openrouter_client = (
            AsyncOpenAI(
                api_key=openrouter_key,
                base_url="https://openrouter.ai/api/v1",
            )
            if AsyncOpenAI is not None and openrouter_key
            else None
        )
        return cls(
            async_openai_client=openai_client,
            async_anthropic_client=anthropic_client,
            async_openrouter_client=openrouter_client,
        )

    def has_provider(self, provider: AIProvider) -> bool:
        if provider == AIProvider.OPENAI:
            return self.async_openai_client is not None
        if provider == AIProvider.ANTHROPIC:
            return self.async_anthropic_client is not None
        if provider == AIProvider.OPENROUTER:
            return self.async_openrouter_client is not None
        return False
