"""
AI Chatbot using OpenAI/Anthropic
Customer support automation
"""
import os
from django.conf import settings
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from .recommendations import get_recommendations
from frontend.seo_models import SEOSettings
from .models import AIConfiguration, AIChatSession, AIChatMessage


class AIChatbot:
    """AI-powered customer support chatbot"""
    
    def __init__(self, provider='openai'):
        self.provider = provider
        
        if provider == 'openai':
            try:
                from openai import OpenAI
                self.client = OpenAI(api_key=settings.OPENAI_API_KEY)
            except ImportError:
                print("OpenAI library not installed")
                self.client = None
        elif provider == 'anthropic':
            try:
                from anthropic import Anthropic
                self.client = Anthropic(api_key=settings.ANTHROPIC_API_KEY)
            except ImportError:
                print("Anthropic library not installed")
                self.client = None
    
    def get_response(self, user_message, conversation_history=None):
        """
        Get AI response to user message
        
        Args:
            user_message: User's message string
            conversation_history: List of previous messages
        
        Returns:
            AI response string
        """
        if not self.client:
            return "AI service is currently unavailable."
        
        system_prompt = self.config.ai_persona
        
        messages = [
            {"role": "system", "content": system_prompt}
        ]
        
        # Add conversation history
        if conversation_history:
            messages.extend(conversation_history)
        
        # Add current message
        messages.append({"role": "user", "content": user_message})
        
        try:
            if self.provider == 'openai':
                response = self.client.chat.completions.create(
                    model="gpt-3.5-turbo",
                    messages=messages,
                    max_tokens=500,
                    temperature=0.7
                )
                return response.choices[0].message.content
            
            elif self.provider == 'anthropic':
                response = self.client.messages.create(
                    model="claude-3-haiku-20240307",
                    max_tokens=500,
                    messages=messages
                )
                return response.content[0].text
        
        except Exception as e:
            print(f"AI Error: {e}")
            return "I'm having trouble processing your request. Please contact our support team."
    
    def get_product_recommendation_text(self, products):
        """
        Generate natural language product recommendations
        """
        if not products:
            return "I couldn't find any specific recommendations at the moment."
        
        product_list = "\n".join([
            f"- {p.name}: ₹{p.price} ({p.average_rating}★)"
            for p in products[:5]
        ])
        
        return f"Based on your preferences, here are some products you might like:\n\n{product_list}"


def get_ai_response(message, history=None, provider='openai'):
    """
    Utility function to get AI chatbot response
    """
    chatbot = AIChatbot(provider=provider)
    return chatbot.get_response(message, history)


@api_view(['POST'])
@permission_classes([AllowAny])
def chat_view(request):
    """AI chat endpoint"""
    try:
        config = AIConfiguration.get_settings()
        if not getattr(config, 'enable_chat', True):
            return Response({'error': 'AI Chat is disabled'}, status=403)
    except Exception:
        pass
    message = request.data.get('message')
    provider = request.data.get('provider', 'openai')
    history = request.data.get('history')
    if not message:
        return Response({'error': 'message is required'}, status=400)
    reply = get_ai_response(message, history, provider)
    return Response({'reply': reply})


@api_view(['GET'])
@permission_classes([AllowAny])
def recommend_view(request):
    """AI product recommendation endpoint"""
    try:
        config = AIConfiguration.get_settings()
        if not getattr(config, 'enable_ai_recommendations', True):
            return Response({'error': 'AI Recommendations are disabled'}, status=403)
    except Exception:
        pass
    from products.models import Product
    recommendation_type = request.GET.get('type', 'trending')
    limit = int(request.GET.get('limit', 6))
    product_id = request.GET.get('product_id')
    product = None
    if product_id:
        try:
            product = Product.objects.get(id=product_id, is_active=True)
        except Product.DoesNotExist:
            product = None
    user = request.user if request.user.is_authenticated else None
    products = get_recommendations(user=user, product=product, recommendation_type=recommendation_type, limit=limit)
    items = [{
        'id': p.id,
        'name': p.name,
        'slug': p.slug,
        'price': float(p.price),
        'on_sale': p.on_sale,
        'image_url': p.featured_image.url if p.featured_image else None
    } for p in products]
    return Response({'products': items})


@api_view(['POST'])
@permission_classes([AllowAny])
def generate_seo_view(request):
    """
    AI-assisted SEO generation for a page.
    Body: { "page_url": "/product/slug/", "page_type": "PRODUCT", "title_hint": "...", "description_hint": "..." }
    """
    try:
        config = AIConfiguration.get_settings()
        if not getattr(config, 'enable_ai_seo', True):
            return Response({'error': 'AI SEO generation is disabled'}, status=403)
    except Exception:
        pass
    page_url = request.data.get('page_url')
    page_type = request.data.get('page_type', 'CUSTOM')
    title_hint = (request.data.get('title_hint') or '').strip()
    description_hint = (request.data.get('description_hint') or '').strip()
    if not page_url:
        return Response({'error': 'page_url is required'}, status=400)
    base_title = title_hint or page_url.strip('/').replace('-', ' ').title()[:60]
    base_desc = description_hint or f"Explore {base_title} at AiBiMagics. Quality products, secure checkout, and fast delivery."[:160]
    meta_title = base_title
    meta_description = base_desc
    og_title = base_title
    og_description = base_desc
    twitter_title = base_title
    twitter_description = base_desc
    try:
        # Try AI refinement if provider available
        provider = request.data.get('provider', 'openai')
        bot = AIChatbot(provider=provider)
        if bot.client:
            prompt = f"Refine this SEO title and description for an e-commerce page.\nTitle: {base_title}\nDescription: {base_desc}\nReturn JSON with keys: title, description."
            reply = bot.get_response(prompt)
            # naive parse
            if isinstance(reply, str) and 'title' in reply:
                import json
                try:
                    data = json.loads(reply)
                    meta_title = (data.get('title') or meta_title)[:70]
                    meta_description = (data.get('description') or meta_description)[:160]
                    og_title = meta_title
                    og_description = meta_description
                    twitter_title = meta_title
                    twitter_description = meta_description
                except Exception:
                    pass
    except Exception:
        pass
    obj, _ = SEOSettings.objects.update_or_create(
        page_url=page_url,
        defaults={
            'page_type': page_type,
            'meta_title': meta_title,
            'meta_description': meta_description,
            'og_title': og_title,
            'og_description': og_description,
            'twitter_title': twitter_title,
            'twitter_description': twitter_description,
            'is_active': True
        }
    )
    return Response({
        'message': 'SEO generated',
        'page_url': obj.page_url,
        'meta_title': obj.meta_title,
        'meta_description': obj.meta_description
    })
