import os
from typing import List, Dict, Any, Optional, Union
from openai import OpenAI
from .utils import simple_retry

# Global client instance
_client = None

def get_client(api_key: Optional[str] = None, base_url: Optional[str] = None) -> OpenAI:
    """Get or create the OpenAI client."""
    global _client
    if _client is None:
        _client = OpenAI(
            api_key=api_key or os.environ.get("OPENAI_API_KEY"),
            base_url=base_url or os.environ.get("OPENAI_BASE_URL")
        )
    return _client

@simple_retry(max_attempts=3)
def call_openai(
    messages: List[Dict[str, str]],
    model: str = "gpt-3.5-turbo",
    temperature: float = 0.7,
    max_tokens: Optional[int] = None,
    client: Optional[OpenAI] = None,
    **kwargs: Any
) -> str:
    """
    Call OpenAI ChatCompletion API with retry logic.
    
    Args:
        messages: List of message dicts (role, content).
        model: Model name.
        temperature: Sampling temperature.
        max_tokens: Max tokens to generate.
        client: Optional OpenAI client instance.
        **kwargs: Additional arguments for client.chat.completions.create.
        
    Returns:
        The content of the first choice message.
    """
    if client is None:
        client = get_client()
        
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
        **kwargs
    )
    
    return response.choices[0].message.content
