"""
AI Service - Unified interface for AI providers
"""
import logging
from typing import Optional, Dict, Any

from .config import settings
from .core import AIProcessingError
from .services.ai.provider_factory import AIProviderFactory, ai_provider_factory


class AIService:
    """Unified service for AI operations with provider fallback"""

    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self._factory: Optional[AIProviderFactory] = None

    @property
    def factory(self) -> AIProviderFactory:
        """Lazy initialization of provider factory"""
        if self._factory is None:
            self._factory = ai_provider_factory
        return self._factory

    def generate_text(
        self,
        prompt: str,
        provider: Optional[str] = None,
        max_tokens: int = 4096
    ) -> str:
        """Generate text using AI provider"""
        try:
            ai_provider = self.factory.get_provider(provider or 'gemini')
            return ai_provider.generate(prompt, max_tokens=max_tokens)
        except AIProcessingError as e:
            self.logger.error(f"AI generation failed: {e}")
            return f"Error: {str(e)}"

    def summarize(self, text: str, **kwargs) -> str:
        """Generate summary of text"""
        try:
            provider = self.factory.get_best_provider()
            return provider.summarize(text, **kwargs)
        except AIProcessingError as e:
            self.logger.error(f"Summarization failed: {e}")
            return f"Error: {str(e)}"

    def correct_text(self, text: str, **kwargs) -> str:
        """Correct grammar and spelling in text"""
        try:
            provider = self.factory.get_best_provider()
            return provider.correct_text(text, **kwargs)
        except AIProcessingError as e:
            self.logger.error(f"Text correction failed: {e}")
            return text  # Return original on error

    def classify_content(self, text: str, **kwargs) -> Dict[str, Any]:
        """Classify content into categories"""
        try:
            provider = self.factory.get_best_provider()
            return provider.classify_content(text, **kwargs)
        except AIProcessingError as e:
            self.logger.error(f"Classification failed: {e}")
            return {"category": "otras_clases", "confidence": 0.0}


# Global instance
ai_service = AIService()
