"""
AI Control System - Automation & Intelligence
Voice Chat, Bulk Operations, Smart Analytics
"""
try:
    import openai
except Exception:
    openai = None
try:
    import anthropic
except Exception:
    anthropic = None
from django.conf import settings
from django.core.mail import send_mass_mail
from django.template.loader import render_to_string
try:
    from twilio.rest import Client as TwilioClient
except Exception:
    TwilioClient = None
try:
    import speech_recognition as sr
except Exception:
    sr = None
try:
    from gtts import gTTS
except Exception:
    gTTS = None
import io


class AIController:
    """
    Main AI Controller for site automation
    """
    
    def __init__(self):
        # Fetch dynamic config
        try:
            from ai_features.models import AIConfiguration
            self.config = AIConfiguration.get_settings()
        except Exception:
            self.config = None
            
        self.openai_key = getattr(self.config, 'openai_api_key', '') or settings.OPENAI_API_KEY
        self.anthropic_key = settings.ANTHROPIC_API_KEY
        if openai and self.openai_key:
            openai.api_key = self.openai_key
        
    def chat_response(self, user_message, context="customer_support"):
        """
        Get AI response for chat
        """
        if self.config and not self.config.enable_auto_chat:
            return "Auto-chat is currently disabled. Please contact support manually."

        system_prompt = getattr(self.config, 'ai_persona', f"You are a helpful {context} assistant for AiBiMagics e-commerce.")
        model_name = getattr(self.config, 'ai_model_name', "gpt-4")

        if openai:
            try:
                response = openai.ChatCompletion.create(
                    model=model_name,
                    messages=[
                        {"role": "system", "content": system_prompt},
                        {"role": "user", "content": user_message}
                    ]
                )
                return response.choices[0].message.content
            except Exception:
                pass
        if anthropic:
            try:
                client = anthropic.Anthropic(api_key=self.anthropic_key)
                message = client.messages.create(
                    model="claude-3-opus-20240229",
                    max_tokens=1024,
                    messages=[{"role": "user", "content": user_message}]
                )
                return message.content[0].text
            except Exception:
                pass
        return "AI service is currently unavailable."

    def voice_to_text(self, audio_file):
        """
        Convert voice to text
        """
        if not sr:
            return None
        try:
            recognizer = sr.Recognizer()
            with sr.AudioFile(audio_file) as source:
                audio = recognizer.record(source)
                try:
                    text = recognizer.recognize_google(audio)
                    return text
                except Exception:
                    return None
        except Exception:
            return None
    
    def text_to_voice(self, text, lang='en'):
        """
        Convert text to voice
        """
        if not gTTS:
            return None
        try:
            tts = gTTS(text=text, lang=lang, slow=False)
            audio_buffer = io.BytesIO()
            tts.write_to_fp(audio_buffer)
            audio_buffer.seek(0)
            return audio_buffer
        except Exception:
            return None
    
    def analyze_customer_sentiment(self, text):
        """
        Analyze customer sentiment
        """
        if not openai:
            return "neutral"
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "Analyze sentiment and return: positive, negative, or neutral"},
                    {"role": "user", "content": text}
                ]
            )
            return response.choices[0].message.content.lower()
        except Exception:
            return "neutral"
    
    def generate_product_description(self, product_name, features):
        """
        AI-generated product descriptions
        """
        prompt = f"Write a compelling product description for {product_name} with these features: {features}"
        if not openai:
            return f"{product_name}: {features}"
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "You are a professional copywriter"},
                    {"role": "user", "content": prompt}
                ]
            )
            return response.choices[0].message.content
        except Exception:
            return f"{product_name}: {features}"
    
    def auto_categorize_product(self, product_name, description):
        """
        Automatically categorize products
        """
        prompt = f"Categorize this product into one category: Electronics, Fashion, Home & Kitchen, Sports, Books, or Beauty.\nProduct: {product_name}\nDescription: {description}"
        if not openai:
            return "General"
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": "Return only the category name"},
                    {"role": "user", "content": prompt}
                ]
            )
            return response.choices[0].message.content.strip()
        except Exception:
            return "General"


class CommunicationController:
    """
    Bulk SMS, Email, and Verification System
    """
    
    def __init__(self):
        # Twilio for SMS
        self.twilio_sid = settings.TWILIO_ACCOUNT_SID
        self.twilio_token = settings.TWILIO_AUTH_TOKEN
        self.twilio_phone = settings.TWILIO_PHONE_NUMBER
        
        if self.twilio_sid and self.twilio_token:
            self.twilio_client = TwilioClient(self.twilio_sid, self.twilio_token)
    
    def send_bulk_sms(self, recipients, message):
        """
        Send SMS to multiple recipients
        Results: {phone: 'sent'/'failed'}
        """
        results = {}
        for phone in recipients:
            try:
                msg = self.twilio_client.messages.create(
                    body=message,
                    from_=self.twilio_phone,
                    to=phone
                )
                results[phone] = 'sent'
            except Exception as e:
                results[phone] = f'failed: {str(e)}'
        return results
    
    def send_verification_sms(self, phone, code):
        """
        Send verification code via SMS
        """
        message = f"AiBiMagics Verification Code: {code}. Valid for 10 minutes."
        try:
            self.twilio_client.messages.create(
                body=message,
                from_=self.twilio_phone,
                to=phone
            )
            return True
        except:
            return False
    
    def send_bulk_emails(self, recipient_list, subject, template_name, context):
        """
        Send promotional emails to multiple users
        recipient_list: [(email, name), ...]
        """
        messages = []
        for email, name in recipient_list:
            context['name'] = name
            html_content = render_to_string(template_name, context)
            from_email = settings.DEFAULT_FROM_EMAIL
            messages.append((subject, '', from_email, [email]))
        
        try:
            send_mass_mail(messages, fail_silently=False)
            return len(messages)
        except Exception as e:
            return 0
    
    def send_verification_email(self, email, code, user_name):
        """
        Send email verification
        """
        subject = "Verify Your Email - AiBiMagics"
        message = f"""
        Hello {user_name},
        
        Your verification code is: {code}
        
        This code is valid for 10 minutes.
        
        Best regards,
        AiBiMagics Team
        """
        
        try:
            send_mail(
                subject,
                message,
                settings.DEFAULT_FROM_EMAIL,
                [email],
                fail_silently=False,
            )
            return True
        except:
            return False
    
    def send_promotional_campaign(self, campaign_data):
        """
        Launch promotional campaign
        campaign_data: {
            'name': 'Summer Sale',
            'sms_message': '...',
            'email_subject': '...',
            'email_template': '...',
            'target_users': QuerySet or list
        }
        """
        results = {
            'sms_sent': 0,
            'emails_sent': 0,
            'failed': 0
        }
        
        # Prepare recipient lists
        sms_recipients = []
        email_recipients = []
        
        for user in campaign_data['target_users']:
            if user.phone and user.phone_verified:
                sms_recipients.append(user.phone)
            if user.email and user.email_verified:
                email_recipients.append((user.email, user.get_full_name()))
        
        # Send SMS
        if sms_recipients and campaign_data.get('sms_message'):
            sms_results = self.send_bulk_sms(sms_recipients, campaign_data['sms_message'])
            results['sms_sent'] = sum(1 for r in sms_results.values() if r == 'sent')
        
        # Send Emails
        if email_recipients and campaign_data.get('email_template'):
            results['emails_sent'] = self.send_bulk_emails(
                email_recipients,
                campaign_data['email_subject'],
                campaign_data['email_template'],
                campaign_data.get('context', {})
            )
        
        return results


class FinancialAnalyzer:
    """
    AI-powered financial analysis for accountants
    """
    
    @staticmethod
    def analyze_revenue_trends(orders_data):
        """
        Analyze revenue trends and predict future
        """
        ai = AIController()
        
        # Prepare data summary
        total_revenue = sum(order.total for order in orders_data if order.is_paid)
        avg_order_value = total_revenue / len(orders_data) if orders_data else 0
        
        prompt = f"""
        Analyze this e-commerce financial data:
        - Total Orders: {len(orders_data)}
        - Total Revenue: ${total_revenue}
        - Average Order Value: ${avg_order_value}
        
        Provide:
        1. Revenue trend analysis
        2. Recommendations for improvement
        3. Predicted next month revenue
        """
        
        analysis = ai.chat_response(prompt, context="financial_analyst")
        return analysis
    
    @staticmethod
    def detect_fraud_patterns(order):
        """
        AI fraud detection
        """
        ai = AIController()
        
        order_details = f"""
        Order Amount: ${order.total}
        Shipping Address: {order.shipping_city}, {order.shipping_country}
        Email: {order.user.email}
        Payment Method: {order.payment_method}
        """
        
        prompt = f"Analyze this order for potential fraud:\n{order_details}\nProvide risk score (0-100) and reasoning."
        
        result = ai.chat_response(prompt, context="fraud_analyst")
        return result


# Export instances
ai_controller = AIController()
communication_controller = CommunicationController()
financial_analyzer = FinancialAnalyzer()
