"""
API client initialization module for LLM providers.
"""

import os

# Lazy imports for optional providers
try:
    from openai import OpenAI
    OPENAI_AVAILABLE = True
except ImportError:
    OPENAI_AVAILABLE = False

try:
    from mistralai import Mistral
    MISTRAL_AVAILABLE = True
except ImportError:
    MISTRAL_AVAILABLE = False

try:
    from groq import Groq
    GROQ_AVAILABLE = True
except ImportError:
    GROQ_AVAILABLE = False


def get_llm_client():
    """
    Initializes and returns the appropriate LLM client based on configuration.
    
    Returns:
        tuple: (client, model_name, provider)
    
    Raises:
        ValueError: If provider is not supported or API key is missing
    """
    # Read configuration from environment at call time (not import time)
    # This ensures YAML config values are picked up
    provider = os.getenv("LLM_PROVIDER", "openai").lower()
    openai_key = os.getenv("OPENAI_API_KEY", "")
    mistral_key = os.getenv("MISTRAL_API_KEY", "")
    groq_key = os.getenv("GROQ_API_KEY", "")
    
    # Model names - read from environment with defaults
    openai_model = os.getenv("YTQGEN_OPENAI_MODEL", "gpt-4o-mini")
    mistral_model = os.getenv("YTQGEN_MISTRAL_MODEL", "mistral-small-latest")
    groq_model = os.getenv("YTQGEN_GROQ_MODEL", "llama-3.3-70b-versatile")
    
    if provider == "openai":
        if not OPENAI_AVAILABLE:
            raise ValueError("OpenAI provider not available. Install with: pip install ytqgen[openai]")
        if not openai_key:
            raise ValueError("OPENAI_API_KEY is not set. Please set it in environment variables.")
        client = OpenAI(api_key=openai_key)
        return client, openai_model, "openai"
    
    elif provider == "mistral":
        if not MISTRAL_AVAILABLE:
            raise ValueError("Mistral provider not available. Install with: pip install ytqgen[mistral]")
        if not mistral_key:
            raise ValueError("MISTRAL_API_KEY is not set. Please set it in environment variables.")
        client = Mistral(api_key=mistral_key)
        return client, mistral_model, "mistral"
    
    elif provider == "groq":
        if not GROQ_AVAILABLE:
            raise ValueError("Groq provider not available. Install with: pip install ytqgen[groq]")
        if not groq_key:
            raise ValueError("GROQ_API_KEY is not set. Please set it in environment variables.")
        client = Groq(api_key=groq_key)
        return client, groq_model, "groq"
    
    else:
        raise ValueError(f"Unsupported LLM provider: {provider}. Supported: openai, mistral, groq")
