import boto3
import json
import pymysql
import re
import smtplib
from email.mime.text import MIMEText
import requests
import logging
from db_config import get_db_connection

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# AWS Configuration
AWS_ACCESS_KEY_ID = "AKIAUWPMKLMSD556YYR5"
AWS_SECRET_ACCESS_KEY = "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"
AWS_REGION = "eu-north-1"
MODEL_ID = "amazon.nova-lite-v1:0"

# WhatsApp Configuration
WHATSAPP_API_URL = "https://rengage.mcube.com/api/wpbox/sendtemplatemessage"  
WHATSAPP_API_TOKEN = "DGw6K3278c1e4y9aF0veYYt5uC90tk7wEVHDJk4G9270b2c2"

# Email Configuration
SMTP_SERVER = "email-smtp.us-east-1.amazonaws.com"
SMTP_PORT = 465
SENDER_EMAIL = "noreply@mcubemail.com"
SMTP_USERNAME = "AKIAUJVLLICOLBGNBZHV"
SMTP_PASSWORD = "BNy8uBvRElGITJRVc/s6HWi9YEyj0v2DK1dhdQABKRkZ"

def get_bedrock_client():
    """Initialize AWS Bedrock client"""
    return boto3.client(
        "bedrock-runtime",
        region_name=AWS_REGION,
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY
    )

def detect_intent(summary_text):
    """Detect intent from call summary using AWS Bedrock"""
    try:
        client = get_bedrock_client()
        
        response = client.invoke_model(
            modelId=MODEL_ID,
            body=json.dumps({
                "messages": [
                    {"role": "user", "content": [
                        {"text": "You are an intent detection system. From the following call summary, extract the main intent."}
                    ]},
                    {"role": "user", "content": [
                        {"text": f"Call Summary: {summary_text}\n\nGive the intent as one of these categories:\n[Product Inquiry, Complaint, Support Request, Billing, Brochure Request, Other]"}
                    ]}
                ],
                "inferenceConfig": {
                    "temperature": 0,
                    "maxTokens": 256
                }
            })
        )

        result = json.loads(response["body"].read())
        intent_detected_raw = result["output"]["message"]["content"][0]["text"].strip()
        
        # Clean and validate intent
        match = re.search(
            r'Product Inquiry|Complaint|Support Request|Billing|Brochure Request|General Inquiry|Pricing|Schedule_Followup',
            intent_detected_raw,
            re.IGNORECASE
        )
        
        if match:
            intent_detected = match.group(0).lower()
        else:
            intent_detected = "other"
            
        logger.info(f"Detected Intent: {intent_detected}")
        return intent_detected
        
    except Exception as e:
        logger.error(f"Error detecting intent: {str(e)}")
        return "other"

def extract_contact_info(summary_text):
    """Extract email and phone from summary text"""
    email_match = re.search(r'[\w\.-]+@[\w\.-]+', summary_text)
    phone_match = re.search(r'\+?\d[\d -]{8,}\d', summary_text)
    
    emp_email = email_match.group(0) if email_match else None
    emp_phone = phone_match.group(0) if phone_match else None
    
    return emp_email, emp_phone

def is_valid_phone(phone):
    """Check if phone number is valid (not 'Not available' or similar)"""
    if not phone:
        return False
    
    # Check for common "not available" patterns
    not_available_patterns = [
        'not available', 'not found', 'n/a', 'na', 'none', 
        'unavailable', 'missing', 'unknown', 'not provided'
    ]
    
    phone_lower = phone.lower().strip()
    if phone_lower in not_available_patterns:
        return False
    
    # Check if it's actually a phone number (contains digits)
    if not re.search(r'\d', phone):
        return False
    
    # Check minimum length for a valid phone number
    digits_only = re.sub(r'\D', '', phone)
    if len(digits_only) < 7:  # Minimum 7 digits for a valid phone
        return False
    
    return True

def is_valid_email(email):
    """Check if email is valid (not 'Not available' or similar)"""
    if not email:
        return False
    
    # Check for common "not available" patterns
    not_available_patterns = [
        'not available', 'not found', 'n/a', 'na', 'none', 
        'unavailable', 'missing', 'unknown', 'not provided'
    ]
    
    email_lower = email.lower().strip()
    if email_lower in not_available_patterns:
        return False
    
    # Check if it's actually an email format
    email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    if not re.match(email_pattern, email):
        return False
    
    return True

def generate_email_body(intent, summary, customer_name=None):
    """Generate email subject and body based on intent"""
    intent = intent.lower()
    
    # Use customer name if available, otherwise use generic greeting
    greeting = f"Dear {customer_name}," if customer_name else "Dear Customer,"
    
    templates = {
        "product inquiry": {
            "subject": "Thank You for Your Interest in MCUBE",
            "body": f"""{greeting}

Thank you for reaching out to us regarding our products. 
We value your interest and our team will share detailed information with you soon.



Best Regards,
MCUBE Team"""
        },
        "complaint": {
            "subject": "We Acknowledge Your Concern",
            "body": f"""{greeting}

We're sorry to hear about the issue you faced. Please be assured that our support team is reviewing your concern and will provide an update shortly.



Sincerely,
MCUBE Support"""
        },
        "support request": {
            "subject": "Support Request Acknowledged",
            "body": f"""{greeting}

We have received your request for support. Our technical team will reach out shortly to assist you.



Regards,
MCUBE Support"""
        },
        "billing": {
            "subject": "Billing Assistance",
            "body": f"""{greeting}

Thank you for contacting us about billing. Our accounts team will get in touch with you soon with the required details.



Best Regards,
MCUBE Billing Team"""
        },
        "brochure request": {
            "subject": "Your Requested Brochure",
            "body": f"""{greeting}

Thank you for requesting our brochure. Please find attached our latest brochure with detailed information about our services.



Regards,
MCUBE Team"""
        },
        "general inquiry": {
            "subject": "We Received Your Inquiry",
            "body": f"""{greeting}

Thank you for reaching out to us. Our team has received your inquiry and will respond with the required information shortly.



Best Regards,
MCUBE Team"""
        },
        "pricing": {
            "subject": "Pricing Information Request",
            "body": f"""{greeting}

We have received your request regarding pricing details. Our sales team will provide you with the relevant information shortly.



Best Regards,
MCUBE Sales Team"""
        },
        "schedule_followup": {
            "subject": "Follow-Up Scheduled",
            "body": f"""{greeting}

We have scheduled a follow-up call/meeting as per your request. Our representative will reach out to you on the agreed date and time.



Best Regards,
MCUBE Team"""
        }
    }
    
    template = templates.get(intent, {
        "subject": "Thank You for Contacting MCUBE",
        "body": f"""{greeting}

Thank you for connecting with us. Our team has received your request and will get in touch with you shortly.



Best Regards,
MCUBE Team"""
    })
    
    return template["subject"], template["body"]

def send_whatsapp_message(phone, intent):
    """Send WhatsApp message based on intent"""
    try:
        logger.info(f"Starting WhatsApp send to {phone} with intent: {intent}")
        
        templates = {
            "complaint": "voice_camplaint",
            "product inquiry": "voice_query",
            "other": "intent_general_template"
        }
        
        template_name = templates.get(intent, "intent_general_template")
        logger.info(f"Using template: {template_name}")
        
        payload = {
            "phone": phone,
            "template_name": template_name,
            "template_language": "en_US",
            "country_code":"91",
            "components": [
                {
                    "type": "body"
                }
            ]
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {WHATSAPP_API_TOKEN}"
        }

        logger.info(f"Sending WhatsApp request to: {WHATSAPP_API_URL}")
        logger.info(f"Payload: {payload}")
        
        # Add timeout to prevent hanging
        response = requests.post(WHATSAPP_API_URL, json=payload, headers=headers, timeout=30)
        
        logger.info(f"WhatsApp API response status: {response.status_code}")
        logger.info(f"WhatsApp API response: {response.text}")
        
        if response.status_code == 200:
            logger.info(f"✅ WhatsApp sent to {phone}")
            return "WhatsApp sent successfully"
        else:
            logger.error(f"❌ WhatsApp failed: {response.text}")
            return "WhatsApp send failed"
            
    except requests.exceptions.Timeout:
        logger.error(f"❌ WhatsApp API timeout for {phone}")
        return "WhatsApp send timeout"
    except requests.exceptions.RequestException as e:
        logger.error(f"❌ WhatsApp API request error: {str(e)}")
        return "WhatsApp send failed"
    except Exception as e:
        logger.error(f"❌ Error sending WhatsApp: {str(e)}")
        return "WhatsApp send failed"

def send_email_message(email, intent, summary, customer_name=None):
    """Send email message based on intent"""
    try:
        subject, body = generate_email_body(intent, summary, customer_name)
        msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = SENDER_EMAIL
        msg['To'] = email

        server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
        server.login(SMTP_USERNAME, SMTP_PASSWORD)
        server.sendmail(SENDER_EMAIL, email, msg.as_string())
        server.quit()
        
        logger.info(f"✅ Email sent to {email}")
        return "Email sent successfully"
        
    except Exception as e:
        logger.error(f"❌ Error sending email: {str(e)}")
        return "Email send failed"

def send_message(call_id, bid):
    """
    Main function to process call and send appropriate message
    
    Args:
        call_id: Call ID to process
        bid: Business ID for dynamic table naming
    """
    try:
        logger.info(f"Processing message for call_id: {call_id}, bid: {bid}")
        
        # Get database connection
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Use dynamic table name based on bid
        calls_table = f"{bid}_calls"
        
        # Get call summary and customer details
        cursor.execute(f"SELECT callid, summary, customer_details FROM {calls_table} WHERE callid = %s AND status = 2", (call_id,))
        row = cursor.fetchone()
        
        if not row:
            logger.warning(f"No summary found for call_id: {call_id}")
            cursor.close()
            conn.close()
            return False, "No summary found"
        
        call_id_from_db, summary_text, customer_details_json = row
        
        # Parse customer details from JSON
        emp_email, emp_phone, customer_name = None, None, None
        if customer_details_json:
            try:
                customer_details = json.loads(customer_details_json)
                emp_email = customer_details.get('email')
                emp_phone = customer_details.get('phone')
                customer_name = customer_details.get('name')
                logger.info(f"Customer details parsed: Name={customer_name}, Phone={emp_phone}, Email={emp_email}")
            except json.JSONDecodeError as e:
                logger.warning(f"Failed to parse customer_details JSON: {e}")
                # Fallback to regex extraction
                emp_email, emp_phone = extract_contact_info(summary_text)
        else:
            # Fallback to regex extraction if no customer_details
            emp_email, emp_phone = extract_contact_info(summary_text)
        
        # Validate contact information
        valid_phone = is_valid_phone(emp_phone)
        valid_email = is_valid_email(emp_email)
        
        if not valid_email and not valid_phone:
            logger.warning(f"No valid email/phone found for call_id: {call_id}. Phone: '{emp_phone}', Email: '{emp_email}'")
            remarks = "No valid contact information found"
        else:
            # Detect intent
            intent_detected = detect_intent(summary_text)
            
            # Send message based on available valid contact method
            if valid_phone:
                logger.info(f"Sending WhatsApp to valid phone: {emp_phone}")
                remarks = send_whatsapp_message(emp_phone, intent_detected)
                logger.info(f"WhatsApp send result: {remarks}")
            elif valid_email:
                logger.info(f"Sending email to valid address: {emp_email}")
                remarks = send_email_message(emp_email, intent_detected, summary_text, customer_name)
                logger.info(f"Email send result: {remarks}")
            else:
                remarks = "No valid contact method available"
        
        # Update call status
        cursor.execute(
            f"UPDATE {calls_table} SET status = 3, remarks = %s WHERE callid = %s",
            (remarks, call_id)
        )
        conn.commit()
        
        cursor.close()
        conn.close()
        
        logger.info(f"✅ Message processed successfully for call_id: {call_id}")
        return True, remarks
        
    except Exception as e:
        logger.error(f"❌ Error processing message for call_id {call_id}: {str(e)}")
        return False, str(e)
