"""OpenAI provider implementation"""

from openai import OpenAI
from typing import List, Dict, Any, Generator
from diona.ai.client.simplecli.models import Message, ChatResponse


class OpenAIProvider:
    """OpenAI provider implementation"""
    
    def __init__(self, base_url: str, api_key: str):
        """Initialize OpenAI provider
        
        Args:
            base_url: OpenAI API base URL
            api_key: OpenAI API key
        """
        self.base_url = base_url
        self.api_key = api_key
        
        # Configure OpenAI client using the new client-based approach
        self.client = OpenAI(
            api_key=api_key,
            base_url=base_url if base_url else "https://api.deepseek.com/v1"
        )
    
    def chat(self, messages: List[Message], model: str, temperature: float = 0.7, max_tokens: int = 1000) -> ChatResponse:
        """Synchronous non-streaming chat
        
        Args:
            messages: List of messages
            model: Model name
            temperature: Temperature for generation
            max_tokens: Maximum tokens to generate
            
        Returns:
            ChatResponse object
        """
        try:
            response = self.client.chat.completions.create(
                model=model,
                messages=[msg.to_dict() for msg in messages],
                temperature=temperature,
                max_tokens=max_tokens
            )
            
            content = response.choices[0].message.content or ""
            finish_reason = response.choices[0].finish_reason
            
            return ChatResponse(
                content=content,
                model=model,
                finish_reason=finish_reason
            )
        except Exception as e:
            print(f"Error in OpenAI chat: {e}")
            return ChatResponse(
                content=f"Error: {str(e)}",
                model=model,
                finish_reason="error"
            )
    
    def chat_stream(self, messages: List[Message], model: str, temperature: float = 0.7, max_tokens: int = 1000) -> Generator[str, None, None]:
        """Streaming chat
        
        Args:
            messages: List of messages
            model: Model name
            temperature: Temperature for generation
            max_tokens: Maximum tokens to generate
            
        Yields:
            Chunks of the response
        """
        try:
            response = self.client.chat.completions.create(
                model=model,
                messages=[msg.to_dict() for msg in messages],
                temperature=temperature,
                max_tokens=max_tokens,
                stream=True
            )
            
            for chunk in response:
                if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
                    yield chunk.choices[0].delta.content
        except Exception as e:
            print(f"Error in OpenAI stream: {e}")
            yield f"Error: {str(e)}"
    
    def validate_api_key(self, model: str = "deepseek-chat") -> bool:
        """Validate API key
        
        Args:
            model: Model name to use for validation
            
        Returns:
            True if API key is valid
        """
        try:
            # Make a simple API call to validate the key
            self.client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": "Hello"}],
                max_tokens=1
            )
            return True
        except Exception as e:
            print(f"API key validation failed: {e}")
            return False


class ProviderManager:
    """Provider manager"""
    
    def __init__(self, base_url: str, api_key: str, model: str = "deepseek-chat"):
        """Initialize provider manager
        
        Args:
            base_url: OpenAI API base URL
            api_key: OpenAI API key
            model: Model name
        """
        self.openai_provider = OpenAIProvider(base_url, api_key)
        self.model = model
    
    def chat(self, messages: List[Message], model: str, temperature: float = 0.7, max_tokens: int = 1000) -> ChatResponse:
        """Synchronous non-streaming chat
        
        Args:
            messages: List of messages
            model: Model name
            temperature: Temperature for generation
            max_tokens: Maximum tokens to generate
            
        Returns:
            ChatResponse object
        """
        return self.openai_provider.chat(messages, model, temperature, max_tokens)
    
    def chat_stream(self, messages: List[Message], model: str, temperature: float = 0.7, max_tokens: int = 1000) -> Generator[str, None, None]:
        """Streaming chat
        
        Args:
            messages: List of messages
            model: Model name
            temperature: Temperature for generation
            max_tokens: Maximum tokens to generate
            
        Yields:
            Chunks of the response
        """
        return self.openai_provider.chat_stream(messages, model, temperature, max_tokens)
    
    def validate_api_key(self) -> bool:
        """Validate API key
        
        Returns:
            True if API key is valid
        """
        return self.openai_provider.validate_api_key(self.model)
