"""
OpenAI Compat Service Extension - Adds Provider Fallback Support
This extends the existing OpenAICompatService with automatic provider cycling
"""
import logging
from typing import Any, Optional
from .provider_fallback import get_provider_fallback_service, ProviderFallbackService

logger = logging.getLogger(__name__)


class OpenAICompatServiceWithFallback:
    """
    Wrapper that adds provider fallback to OpenAICompatService
    """
    
    def __init__(self, openai_compat_service):
        """
        Args:
            openai_compat_service: The existing OpenAICompatService instance
        """
        self.service = openai_compat_service
        self.fallback_service = get_provider_fallback_service()
    
    async def create_chat_completion_with_fallback(
        self,
        request,
        stream: bool = False
    ) -> Optional[Any]:
        """
        Try chat completion with automatic provider fallback.
        
        Args:
            request: ChatCompletionRequest
            stream: Whether to stream response
            
        Returns:
            Response from first successful provider, or None if all failed
        """
        # Convert request to messages format
        messages = self._serialize_messages_for_fallback(request)
        
        # Extract model and other params
        model = getattr(request, 'model', None) or 'gpt-4o-mini'
        
        # Build kwargs from request
        kwargs = {
            'temperature': getattr(request, 'temperature', 0.7),
            'max_tokens': getattr(request, 'max_tokens', 2048),
            'top_p': getattr(request, 'top_p', 1.0),
            'stream': stream,
        }
        
        logger.info(f"Attempting OpenAI compat completion with fallback (model: {model})")
        
        # Try with fallback system
        response, attempts = await self.fallback_service.complete_with_fallback(
            messages=messages,
            fallback_model=model,
            **kwargs
        )
        
        if response:
            logger.info(f"✓ OpenAI compat completion succeeded via fallback")
            # Normalize response to OpenAI format
            return self._normalize_fallback_response(response, model)
        
        # All fallback attempts failed
        logger.error("All fallback providers failed for OpenAI compat request")
        return None
    
    def _serialize_messages_for_fallback(self, request) -> list[dict]:
        """Convert ChatCompletionRequest to litellm message format"""
        messages = []
        
        if hasattr(request, 'messages') and request.messages:
            for msg in request.messages:
                msg_dict = {"role": msg.role, "content": msg.content}
                messages.append(msg_dict)
        
        return messages
    
    def _normalize_fallback_response(self, response: Any, model: str) -> Any:
        """
        Normalize litellm response to OpenAI format.
        Returns a ChatCompletionResponse-like object.
        """
        # This creates a simple dict that mimics OpenAI response structure
        # The actual OpenAICompatService._normalize_chat_completion_response
        # can handle this
        
        try:
            if hasattr(response, 'model_dump'):
                # Pydantic model
                return response
            elif isinstance(response, dict):
                # Already a dict
                return response
            else:
                # litellm response object - convert to dict
                return {
                    "id": getattr(response, "id", f"chatcmpl-{id(response)}"),
                    "object": "chat.completion",
                    "created": getattr(response, "created", 0),
                    "model": model,
                    "choices": getattr(response, "choices", []),
                    "usage": getattr(response, "usage", None),
                }
        except Exception as e:
            logger.error(f"Error normalizing fallback response: {e}")
            return response
    
    def list_providers(self) -> list[dict]:
        """List all configured providers"""
        return self.fallback_service.list_providers()
    
    def enable_provider(self, name: str) -> bool:
        """Enable a specific provider"""
        return self.fallback_service.enable_provider(name)
    
    def disable_provider(self, name: str) -> bool:
        """Disable a specific provider"""
        return self.fallback_service.disable_provider(name)


def add_fallback_to_openai_compat(openai_compat_service) -> OpenAICompatServiceWithFallback:
    """
    Add fallback capability to an existing OpenAICompatService instance.
    
    Args:
        openai_compat_service: The existing OpenAICompatService instance
        
    Returns:
        OpenAICompatServiceWithFallback wrapper with fallback capability
    """
    return OpenAICompatServiceWithFallback(openai_compat_service)
