"""
AI Configuration & Site Control
Replaces the old SiteConfiguration with a more advanced AI-driven model.
"""
from django.db import models
from django.core.cache import cache
from django.conf import settings

class AIConfiguration(models.Model):
    """
    Central AI Control System for the entire site.
    Manages branding, settings, and AI automation behavior.
    """
    
    # AI & Automation Settings (New Features)
    enable_auto_chat = models.BooleanField(default=True, help_text="Enable AI to automatically reply to customer chats")
    ai_persona = models.TextField(
        default="You are a helpful, professional AI assistant for AiBiMagics. You help customers find products, track orders, and answer questions.",
        help_text="System prompt defining the AI's personality and rules."
    )
    
    MODEL_CHOICES = [
        ('gpt-4', 'GPT-4'),
        ('gpt-4-turbo', 'GPT-4 Turbo'),
        ('gpt-3.5-turbo', 'GPT-3.5 Turbo'),
        ('gpt-4o', 'GPT-4o'),
        ('gemini-pro', 'Gemini Pro'),
        ('claude-3-opus', 'Claude 3 Opus'),
        ('claude-3-sonnet', 'Claude 3 Sonnet'),
    ]
    ai_model_name = models.CharField(
        max_length=50, 
        choices=MODEL_CHOICES,
        default="gpt-4", 
        help_text="AI Model to use"
    )
    openai_api_key = models.CharField(max_length=200, blank=True, help_text="API Key for OpenAI (overrides settings if provided)")
    
    # --- Migrated SiteConfiguration Fields ---
    
    # Hero Section
    hero_title = models.CharField(max_length=200, default='Welcome to AiBiMagics', help_text='Main heading for the hero section')
    hero_subtitle = models.TextField(default='Your AI-Powered Shopping Destination', help_text='Subtitle/description for the hero section')
    hero_background_image = models.ImageField(upload_to='hero/', blank=True, null=True, help_text='Background image for the hero section')
    hero_button_text = models.CharField(max_length=50, default='Shop Now', help_text='Text for the primary CTA button')
    hero_button_link = models.CharField(max_length=200, default='/products/', help_text='Link for the primary CTA button')

    # Basic Information
    site_name = models.CharField(max_length=200, default='AiBiMagics')
    site_tagline = models.CharField(max_length=300, default='Your AI-Powered Shopping Destination')
    site_description = models.TextField(default='Amazing products with AI-powered recommendations')
    
    # Logo & Branding
    logo = models.ImageField(upload_to='branding/', blank=True, null=True, help_text='Main site logo')
    logo_dark = models.ImageField(upload_to='branding/', blank=True, null=True, help_text='Dark version of logo')
    favicon = models.ImageField(upload_to='branding/', blank=True, null=True, help_text='16x16 or 32x32 favicon')
    
    # Contact Information
    contact_email = models.EmailField(default='contact@aibimagics.com', blank=True, help_text="Contact email")
    support_email = models.EmailField(default='support@aibimagics.com', blank=True)
    sales_email = models.EmailField(default='sales@aibimagics.com', blank=True)
    phone = models.CharField(max_length=20, blank=True)
    whatsapp = models.CharField(max_length=20, blank=True, help_text='With country code, e.g., +1234567890')
    
    # Address
    address_line1 = models.CharField(max_length=255, blank=True)
    address_line2 = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=100, blank=True)
    state = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    postal_code = models.CharField(max_length=20, blank=True)
    
    # Social Media Links
    facebook_url = models.URLField(blank=True)
    twitter_url = models.URLField(blank=True)
    instagram_url = models.URLField(blank=True)
    linkedin_url = models.URLField(blank=True)
    youtube_url = models.URLField(blank=True)
    pinterest_url = models.URLField(blank=True)
    tiktok_url = models.URLField(blank=True)
    telegram_url = models.URLField(blank=True)
    
    # Business Hours
    business_hours = models.TextField(
        blank=True,
        default='Monday - Friday: 9:00 AM - 6:00 PM\nSaturday: 10:00 AM - 4:00 PM\nSunday: Closed'
    )
    
    # SEO Settings
    meta_keywords = models.TextField(blank=True, help_text='Comma-separated keywords')
    meta_description = models.TextField(blank=True)
    google_analytics_id = models.CharField(max_length=50, blank=True, help_text='GA4 Measurement ID')
    google_tag_manager_id = models.CharField(max_length=50, blank=True)
    facebook_pixel_id = models.CharField(max_length=50, blank=True)
    
    # Email Settings
    email_from_address = models.EmailField(default='no-reply@aibimagics.com', help_text="Default 'From' email address", blank=True)
    smtp_host = models.CharField(max_length=200, blank=True, default='smtp.gmail.com')
    smtp_port = models.IntegerField(default=587)
    smtp_username = models.CharField(max_length=200, blank=True)
    smtp_password = models.CharField(max_length=200, blank=True)
    smtp_use_tls = models.BooleanField(default=True)
    
    # Twilio SMS Settings
    twilio_account_sid = models.CharField(max_length=255, blank=True, null=True, help_text="Twilio Account SID")
    twilio_auth_token = models.CharField(max_length=255, blank=True, null=True, help_text="Twilio Auth Token")
    twilio_phone_number = models.CharField(max_length=50, blank=True, null=True, help_text="Twilio From Phone Number")
    
    # Notification Emails (who receives notifications)
    admin_notification_email = models.EmailField(default='admin@aibimagics.com', blank=True)
    order_notification_email = models.EmailField(default='orders@aibimagics.com', blank=True)
    
    # Footer Content
    footer_about = models.TextField(
        blank=True,
        default='AiBiMagics is your trusted e-commerce platform powered by AI.'
    )
    copyright_text = models.CharField(
        max_length=300,
        default='© 2025 AiBiMagics. All rights reserved.'
    )
    
    # Features Toggles
    enable_chat = models.BooleanField(default=True, help_text='Enable live chat widget')
    enable_newsletter = models.BooleanField(default=True)
    enable_wishlist = models.BooleanField(default=True)
    enable_reviews = models.BooleanField(default=True)
    enable_ai_recommendations = models.BooleanField(default=True)
    enable_ai_seo = models.BooleanField(default=True)
    
    # Bank API
    bank_api_base_url = models.CharField(max_length=300, blank=True, help_text='Base URL of Bank API')
    bank_api_token = models.CharField(max_length=300, blank=True, help_text='Bearer token for Bank API')
    
    # Maintenance Mode
    maintenance_mode = models.BooleanField(default=False)
    maintenance_message = models.TextField(
        blank=True,
        default='We are currently undergoing maintenance. We will be back shortly!'
    )
    maintenance_end_time = models.DateTimeField(null=True, blank=True)
    maintenance_access_mode = models.CharField(
        max_length=20,
        default='SUPERUSER_ONLY',
        choices=[
            ('SUPERUSER_ONLY', 'Superuser Only'),
            ('STAFF_ONLY', 'Staff Only'),
            ('REGISTERED_ONLY', 'Registered Users Only'),
        ]
    )
    
    # Custom CSS/JS
    THEME_CHOICES = [
        ('orange', 'Orange (Original)'),
        ('pink', 'Pink (Modern)'),
        ('blue', 'Blue (Professional)'),
        ('green', 'Green (Eco)'),
        ('purple', 'Purple (Creative)'),
        ('red', 'Red (Bold)'),
        ('teal', 'Teal (Fresh)'),
        ('indigo', 'Indigo (Deep)'),
        ('yellow', 'Yellow (Sunny)'),
        ('cyan', 'Cyan (Cool)'),
        ('lime', 'Lime (Vibrant)'),
        ('amber', 'Amber (Warm)'),
        ('brown', 'Brown (Earth)'),
        ('slate', 'Slate (Neutral)'),
        ('dark', 'Dark (Elegant)'),
        ('custom', 'Custom (Manual Entry)'),
    ]
    theme_color = models.CharField(
        max_length=20,
        choices=THEME_CHOICES,
        default='orange',
        help_text='Primary color theme for the site'
    )
    
    # CSS Color Variables (Populated by theme_color or manual entry)
    primary_color = models.CharField(max_length=20, default='#FF9900', help_text='Main brand color')
    primary_hover = models.CharField(max_length=20, default='#E47911', help_text='Hover state for primary color')
    secondary_color = models.CharField(max_length=20, default='#232F3E', help_text='Secondary/Background color')
    accent_color = models.CharField(max_length=20, default='#146EB4', help_text='Accent/Link color')
    
    # Status Colors
    success_color = models.CharField(max_length=20, default='#28a745', help_text='Success messages/badges')
    warning_color = models.CharField(max_length=20, default='#ffc107', help_text='Warning messages/badges')
    error_color = models.CharField(max_length=20, default='#dc3545', help_text='Error messages/badges')
    info_color = models.CharField(max_length=20, default='#17a2b8', help_text='Info messages/badges')

    primary_shadow = models.CharField(max_length=50, default='rgba(255, 153, 0, 0.3)', help_text='Shadow color (rgba)')
    primary_light = models.CharField(max_length=50, default='rgba(255, 153, 0, 0.1)', help_text='Light background variation (rgba)')

    custom_css = models.TextField(blank=True, help_text='Custom CSS to inject into all pages')
    custom_js = models.TextField(blank=True, help_text='Custom JavaScript to inject into all pages')
    header_scripts = models.TextField(blank=True, help_text='Scripts to add in <head>')
    footer_scripts = models.TextField(blank=True, help_text='Scripts to add before </body>')
    tax_rate_percent = models.DecimalField(max_digits=5, decimal_places=2, default=18)
    free_shipping_threshold = models.DecimalField(max_digits=10, decimal_places=2, default=500)
    shipping_flat_amount = models.DecimalField(max_digits=10, decimal_places=2, default=50)
    
    # Timestamps
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'AI Site Control'
        verbose_name_plural = 'AI Site Control'
    
    def __str__(self):
        return f"AI System Control ({self.site_name})"
    
    @property
    def has_custom_description(self):
        desc = (self.site_description or '').strip()
        if not desc:
            return False
        placeholders = [
            'Amazing products with AI-powered recommendations',
            'Amazing products with AI-powered recommendations. Your trusted e-commerce platform for quality products and exceptional service.'
        ]
        return desc not in placeholders
    
    def apply_theme_colors(self):
        """Apply color values based on selected theme"""
        if self.theme_color == 'custom':
            return

        themes = {
            'orange': {
                'primary_color': '#FF9900',
                'primary_hover': '#E88A00',
                'secondary_color': '#232F3E',
                'accent_color': '#146EB4',
                'primary_shadow': 'rgba(255, 153, 0, 0.3)',
                'primary_light': 'rgba(255, 153, 0, 0.1)',
            },
            'blue': {
                'primary_color': '#2196F3',
                'primary_hover': '#1976D2',
                'secondary_color': '#263238',
                'accent_color': '#FFC107',
                'primary_shadow': 'rgba(33, 150, 243, 0.3)',
                'primary_light': 'rgba(33, 150, 243, 0.1)',
            },
            'green': {
                'primary_color': '#4CAF50',
                'primary_hover': '#388E3C',
                'secondary_color': '#1B5E20',
                'accent_color': '#CDDC39',
                'primary_shadow': 'rgba(76, 175, 80, 0.3)',
                'primary_light': 'rgba(76, 175, 80, 0.1)',
            },
            'purple': {
                'primary_color': '#9C27B0',
                'primary_hover': '#7B1FA2',
                'secondary_color': '#4A148C',
                'accent_color': '#E040FB',
                'primary_shadow': 'rgba(156, 39, 176, 0.3)',
                'primary_light': 'rgba(156, 39, 176, 0.1)',
            },
            'red': {
                'primary_color': '#F44336',
                'primary_hover': '#D32F2F',
                'secondary_color': '#B71C1C',
                'accent_color': '#FF5252',
                'primary_shadow': 'rgba(244, 67, 54, 0.3)',
                'primary_light': 'rgba(244, 67, 54, 0.1)',
            },
            'teal': {
                'primary_color': '#009688',
                'primary_hover': '#00796B',
                'secondary_color': '#004D40',
                'accent_color': '#FFC107',
                'primary_shadow': 'rgba(0, 150, 136, 0.3)',
                'primary_light': 'rgba(0, 150, 136, 0.1)',
            },
            'indigo': {
                'primary_color': '#3F51B5',
                'primary_hover': '#303F9F',
                'secondary_color': '#1A237E',
                'accent_color': '#FF4081',
                'primary_shadow': 'rgba(63, 81, 181, 0.3)',
                'primary_light': 'rgba(63, 81, 181, 0.1)',
            },
            'yellow': {
                'primary_color': '#FFC107',
                'primary_hover': '#FFA000',
                'secondary_color': '#212121',
                'accent_color': '#2196F3',
                'primary_shadow': 'rgba(255, 193, 7, 0.3)',
                'primary_light': 'rgba(255, 193, 7, 0.1)',
            },
            'dark': {
                'primary_color': '#212121',
                'primary_hover': '#000000',
                'secondary_color': '#424242',
                'accent_color': '#E91E63',
                'primary_shadow': 'rgba(33, 33, 33, 0.3)',
                'primary_light': 'rgba(33, 33, 33, 0.1)',
            },
            'pink': {
                'primary_color': '#E91E63',
                'primary_hover': '#C2185B',
                'secondary_color': '#232F3E',
                'accent_color': '#146EB4',
                'primary_shadow': 'rgba(233, 30, 99, 0.3)',
                'primary_light': 'rgba(233, 30, 99, 0.1)',
            },
            'cyan': {
                'primary_color': '#00BCD4',
                'primary_hover': '#0097A7',
                'secondary_color': '#006064',
                'accent_color': '#FF5722',
                'primary_shadow': 'rgba(0, 188, 212, 0.3)',
                'primary_light': 'rgba(0, 188, 212, 0.1)',
            },
            'lime': {
                'primary_color': '#CDDC39',
                'primary_hover': '#AFB42B',
                'secondary_color': '#33691E',
                'accent_color': '#673AB7',
                'primary_shadow': 'rgba(205, 220, 57, 0.3)',
                'primary_light': 'rgba(205, 220, 57, 0.1)',
            },
            'amber': {
                'primary_color': '#FFC107',
                'primary_hover': '#FFB300',
                'secondary_color': '#3E2723',
                'accent_color': '#2196F3',
                'primary_shadow': 'rgba(255, 193, 7, 0.3)',
                'primary_light': 'rgba(255, 193, 7, 0.1)',
            },
            'brown': {
                'primary_color': '#795548',
                'primary_hover': '#5D4037',
                'secondary_color': '#3E2723',
                'accent_color': '#FFC107',
                'primary_shadow': 'rgba(121, 85, 72, 0.3)',
                'primary_light': 'rgba(121, 85, 72, 0.1)',
            },
            'slate': {
                'primary_color': '#607D8B',
                'primary_hover': '#455A64',
                'secondary_color': '#263238',
                'accent_color': '#FF5722',
                'primary_shadow': 'rgba(96, 125, 139, 0.3)',
                'primary_light': 'rgba(96, 125, 139, 0.1)',
            }
        }
        
        colors = themes.get(self.theme_color, themes['pink'])
        for key, value in colors.items():
            setattr(self, key, value)

    def save(self, *args, **kwargs):
        # Ensure only one instance exists
        if not self.pk and AIConfiguration.objects.exists():
            # Update existing instead of creating new
            existing = AIConfiguration.objects.first()
            self.pk = existing.pk
        
        # Apply theme colors
        self.apply_theme_colors()
        
        # Clear cache when settings are updated
        cache.delete('ai_configuration')
        
        super().save(*args, **kwargs)
    
    @classmethod
    def get_settings(cls):
        """Get settings with caching"""
        settings = cache.get('ai_configuration')
        if settings is None:
            settings = cls.objects.first()
            if settings:
                cache.set('ai_configuration', settings, 3600)  # Cache for 1 hour
            else:
                # Create default settings if none exist
                settings = cls.objects.create()
                cache.set('ai_configuration', settings, 3600)
        return settings

class AIChatSession(models.Model):
    """
    Stores AI Chat sessions for history and context.
    """
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='ai_chat_sessions')
    session_id = models.CharField(max_length=100, unique=True, help_text="Session ID for anonymous users")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-updated_at']
        
    def __str__(self):
        return f"Chat {self.session_id} ({self.user or 'Anonymous'})"

class CommunicationTemplate(models.Model):
    """
    Templates for Email, SMS, and WhatsApp communications.
    """
    TYPE_CHOICES = [
        ('email', 'Email'),
        ('sms', 'SMS'),
        ('whatsapp', 'WhatsApp'),
    ]
    
    CATEGORY_CHOICES = [
        ('promotional', 'Promotional'),
        ('transactional', 'Transactional'),
        ('newsletter', 'Newsletter'),
        ('notification', 'Notification'),
        ('other', 'Other'),
    ]
    
    name = models.CharField(max_length=200, help_text="Internal name for the template")
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='email')
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='other')
    subject = models.CharField(max_length=255, blank=True, help_text="Subject line (for Email only)")
    content = models.TextField(help_text="Message content. You can use {{ user.first_name }}, {{ user.last_name }} as placeholders.")
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['name']
        verbose_name = "Communication Template"
        verbose_name_plural = "Communication Templates"

    def __str__(self):
        return f"{self.name} ({self.get_type_display()})"

class AIChatMessage(models.Model):
    """
    Individual messages in an AI chat session.
    """
    ROLE_CHOICES = [
        ('user', 'User'),
        ('assistant', 'AI Assistant'),
        ('system', 'System'),
    ]
    
    session = models.ForeignKey(AIChatSession, on_delete=models.CASCADE, related_name='messages')
    role = models.CharField(max_length=20, choices=ROLE_CHOICES)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['created_at']
        
    def __str__(self):
        return f"{self.role}: {self.content[:50]}"
