from openai import AsyncOpenAI
from groq import AsyncGroq
import bilbystats as bs

_deepseek_client = None
_groq_client = None
_openai_client = None
_openrouter_client = None


async def get_openai_client(model_name: str, timeout):
    """Get or create a reusable async OpenAI client"""
    global _openai_client, _deepseek_client, _openrouter_client, _groq_client
    
    available_models = bs.read_data("api_model_dict.json")
    
    if model_name[len(model_name) - 5:] == ':groq':
        _groq_client = AsyncGroq(api_key=bs.read_api_key("groq"), timeout=timeout)
        return _groq_client
        
    if model_name in available_models["openai"]:
        if _openai_client is None:
            _openai_client = AsyncOpenAI(api_key=bs.read_api_key("openai"), timeout=timeout)
        return _openai_client
    
    elif model_name in available_models["deepseek"]:
        if _deepseek_client is None:
            _deepseek_client = AsyncOpenAI(
                api_key=bs.read_api_key("deepseek"),
                base_url="https://api.deepseek.com",
            )
        return _deepseek_client
    
    else:
        if _openrouter_client is None:
            _openrouter_client = AsyncOpenAI(
                base_url="https://openrouter.ai/api/v1",
                api_key=bs.read_api_key('openrouter'),
                timeout = timeout
            )
        return _openrouter_client