"""
Email Service for License Delivery

Handles automated email delivery of license keys with templates.
"""

import os
import logging
from typing import Dict, Any, Optional
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import json

logger = logging.getLogger(__name__)

# Email configuration from environment
SMTP_HOST = os.getenv("SMTP_HOST", "smtp.gmail.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USERNAME = os.getenv("SMTP_USERNAME")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD")
FROM_EMAIL = os.getenv("FROM_EMAIL", "noreply@cerebion.com")
FROM_NAME = os.getenv("FROM_NAME", "Cerebion Rivet")


class EmailService:
    """Service for sending license-related emails"""

    @staticmethod
    def send_otp_email(to_email: str, customer_name: str, otp: str) -> bool:
        """
        Send a trial signup verification code (OTP) to the customer.

        Args:
            to_email: Recipient email address
            customer_name: Customer's first/full name
            otp: 6-digit one-time password

        Returns:
            bool: True if email sent (or gracefully skipped in dev mode)
        """
        try:
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Your Cerebion Rivet Verification Code"
            msg['From'] = f"{FROM_NAME} <{FROM_EMAIL}>"
            msg['To'] = to_email

            text_content = f"""Hi {customer_name},

Your Cerebion Rivet verification code is:

    {otp}

This code expires in 10 minutes. Do not share it with anyone.

Best regards,
The Cerebion Team
"""

            html_content = f"""<html><body style="font-family:sans-serif;color:#333;">
<p>Hi {customer_name},</p>
<p>Your Cerebion Rivet verification code is:</p>
<div style="margin:24px 0;text-align:center;">
  <span style="font-size:36px;font-weight:bold;letter-spacing:12px;font-family:monospace;">{otp}</span>
</div>
<p style="color:#666;font-size:13px;">This code expires in 10 minutes. Do not share it with anyone.</p>
<br>
<p>Best regards,<br>The Cerebion Team</p>
</body></html>"""

            msg.attach(MIMEText(text_content, 'plain'))
            msg.attach(MIMEText(html_content, 'html'))

            return EmailService._send_email(msg, to_email)

        except Exception as e:
            logger.error(f"Failed to send OTP email to {to_email}: {e}")
            return False

    @staticmethod
    def send_license_key_email(
        to_email: str,
        customer_name: str,
        license_key: str,
        license_type: str,
        expires_at: str,
        seats: int = 1
    ) -> bool:
        """
        Send license key delivery email to customer.
        
        Args:
            to_email: Customer email address
            customer_name: Customer name
            license_key: Generated license key
            license_type: Type of license (trial, professional, enterprise)
            expires_at: License expiration date
            seats: Number of seats included
            
        Returns:
            bool: True if email sent successfully
        """
        try:
            # Create email message
            msg = MIMEMultipart('alternative')
            msg['Subject'] = f"Your Cerebion Rivet {license_type.title()} License Key"
            msg['From'] = f"{FROM_NAME} <{FROM_EMAIL}>"
            msg['To'] = to_email
            
            # Generate email content
            html_content = EmailService._generate_license_email_html(
                customer_name=customer_name,
                license_key=license_key,
                license_type=license_type,
                expires_at=expires_at,
                seats=seats
            )
            
            text_content = EmailService._generate_license_email_text(
                customer_name=customer_name,
                license_key=license_key,
                license_type=license_type,
                expires_at=expires_at,
                seats=seats
            )
            
            # Attach content
            msg.attach(MIMEText(text_content, 'plain'))
            msg.attach(MIMEText(html_content, 'html'))
            
            # Send email
            return EmailService._send_email(msg, to_email)
            
        except Exception as e:
            logger.error(f"Failed to send license key email to {to_email}: {e}")
            return False
    
    @staticmethod
    def send_license_activation_notification(
        to_email: str,
        customer_name: str,
        license_key: str,
        device_name: str,
        activation_time: str
    ) -> bool:
        """
        Send license activation notification email.
        
        Args:
            to_email: Customer email address
            customer_name: Customer name
            license_key: Activated license key
            device_name: Name of activated device
            activation_time: When license was activated
            
        Returns:
            bool: True if email sent successfully
        """
        try:
            msg = MIMEMultipart('alternative')
            msg['Subject'] = "Cerebion Rivet License Activated"
            msg['From'] = f"{FROM_NAME} <{FROM_EMAIL}>"
            msg['To'] = to_email
            
            html_content = f"""
            <html>
            <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                    <h2 style="color: #2563eb;">License Activation Notification</h2>
                    
                    <p>Hello {customer_name},</p>
                    
                    <p>Your Cerebion Rivet license has been successfully activated:</p>
                    
                    <div style="background: #f8fafc; padding: 15px; border-radius: 5px; margin: 20px 0;">
                        <strong>License Key:</strong> {license_key}<br>
                        <strong>Device:</strong> {device_name}<br>
                        <strong>Activated:</strong> {activation_time}
                    </div>
                    
                    <p>If this activation was not performed by you, please contact our support team immediately.</p>
                    
                    <p>Best regards,<br>The Cerebion Team</p>
                    
                    <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;">
                    <p style="font-size: 12px; color: #6b7280;">
                        Support: support@cerebion.com | Website: https://cerebion.com
                    </p>
                </div>
            </body>
            </html>
            """
            
            text_content = f"""
License Activation Notification

Hello {customer_name},

Your Cerebion Rivet license has been successfully activated:

License Key: {license_key}
Device: {device_name}
Activated: {activation_time}

If this activation was not performed by you, please contact our support team immediately.

Best regards,
The Cerebion Team

Support: support@cerebion.com | Website: https://cerebion.com
            """
            
            msg.attach(MIMEText(text_content, 'plain'))
            msg.attach(MIMEText(html_content, 'html'))
            
            return EmailService._send_email(msg, to_email)
            
        except Exception as e:
            logger.error(f"Failed to send activation notification to {to_email}: {e}")
            return False
    
    @staticmethod
    def _generate_license_email_html(
        customer_name: str,
        license_key: str,
        license_type: str,
        expires_at: str,
        seats: int
    ) -> str:
        """Generate HTML email template for license delivery"""
        expiry_date = datetime.fromisoformat(expires_at.replace('Z', '+00:00')).strftime('%B %d, %Y')
        
        return f"""
        <html>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="text-align: center; margin-bottom: 30px;">
                    <h1 style="color: #2563eb;">Cerebion Rivet</h1>
                    <h2 style="color: #374151;">Your License Key is Ready!</h2>
                </div>
                
                <p>Hello {customer_name},</p>
                
                <p>Thank you for purchasing Cerebion Rivet! Your {license_type} license is now ready to use.</p>
                
                <div style="background: #f0f9ff; border: 2px solid #2563eb; padding: 20px; border-radius: 8px; margin: 25px 0; text-align: center;">
                    <h3 style="margin-top: 0; color: #1e40af;">Your License Key</h3>
                    <div style="font-family: 'Courier New', monospace; font-size: 18px; font-weight: bold; color: #1e40af; background: white; padding: 15px; border-radius: 4px; letter-spacing: 1px;">
                        {license_key}
                    </div>
                </div>
                
                <div style="background: #f8fafc; padding: 15px; border-radius: 5px; margin: 20px 0;">
                    <h4 style="margin-top: 0;">License Details:</h4>
                    <ul style="margin: 0; padding-left: 20px;">
                        <li><strong>Type:</strong> {license_type.title()}</li>
                        <li><strong>Seats:</strong> {seats} device(s)</li>
                        <li><strong>Expires:</strong> {expiry_date}</li>
                    </ul>
                </div>
                
                <h3>How to Activate Your License:</h3>
                <ol>
                    <li>Open Cerebion Rivet application</li>
                    <li>Go to <strong>Settings → License Management</strong></li>
                    <li>Click the <strong>"Online License"</strong> tab</li>
                    <li>Enter your license key in the input field</li>
                    <li>Click <strong>"Activate License"</strong></li>
                </ol>
                
                <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0;">
                    <strong>Important:</strong> Keep this license key safe! You'll need it to activate Rivet on your devices.
                </div>
                
                <h3>Need Help?</h3>
                <p>If you have any questions or need assistance:</p>
                <ul>
                    <li>📧 Email: <a href="mailto:support@cerebion.com">support@cerebion.com</a></li>
                    <li>📖 Documentation: <a href="https://docs.cerebion.com">docs.cerebion.com</a></li>
                    <li>💬 Support Portal: <a href="https://support.cerebion.com">support.cerebion.com</a></li>
                </ul>
                
                <p>Welcome to Cerebion Rivet! We're excited to help you secure your quantum-vulnerable systems.</p>
                
                <p>Best regards,<br>The Cerebion Team</p>
                
                <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;">
                <p style="font-size: 12px; color: #6b7280; text-align: center;">
                    © 2024 Cerebion LLC. All rights reserved.<br>
                    This email contains confidential license information. Please do not share.
                </p>
            </div>
        </body>
        </html>
        """
    
    @staticmethod
    def _generate_license_email_text(
        customer_name: str,
        license_key: str,
        license_type: str,
        expires_at: str,
        seats: int
    ) -> str:
        """Generate plain text email template for license delivery"""
        expiry_date = datetime.fromisoformat(expires_at.replace('Z', '+00:00')).strftime('%B %d, %Y')
        
        return f"""
CEREBION RIVET - YOUR LICENSE KEY IS READY!

Hello {customer_name},

Thank you for purchasing Cerebion Rivet! Your {license_type} license is now ready to use.

YOUR LICENSE KEY: {license_key}

License Details:
- Type: {license_type.title()}
- Seats: {seats} device(s)
- Expires: {expiry_date}

HOW TO ACTIVATE YOUR LICENSE:
1. Open Cerebion Rivet application
2. Go to Settings → License Management
3. Click the "Online License" tab
4. Enter your license key in the input field
5. Click "Activate License"

IMPORTANT: Keep this license key safe! You'll need it to activate Rivet on your devices.

NEED HELP?
If you have any questions or need assistance:
- Email: support@cerebion.com
- Documentation: https://docs.cerebion.com
- Support Portal: https://support.cerebion.com

Welcome to Cerebion Rivet! We're excited to help you secure your quantum-vulnerable systems.

Best regards,
The Cerebion Team

---
© 2024 Cerebion LLC. All rights reserved.
This email contains confidential license information. Please do not share.
        """
    
    @staticmethod
    def _send_email(msg: MIMEMultipart, to_email: str) -> bool:
        """Send email via SMTP"""
        if not SMTP_USERNAME or not SMTP_PASSWORD:
            logger.warning("SMTP credentials not configured - email not sent")
            logger.info(f"Would send email to {to_email}: {msg['Subject']}")
            return True  # Return True in development mode
        
        try:
            with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
                server.starttls()
                server.login(SMTP_USERNAME, SMTP_PASSWORD)
                server.send_message(msg)
            
            logger.info(f"Email sent successfully to {to_email}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send email to {to_email}: {e}")
            return False
    
    @staticmethod
    def send_license_revocation_notification(
        license_key: str,
        reason: str
    ) -> bool:
        """
        Send license revocation notification.
        
        Args:
            license_key: Revoked license key
            reason: Reason for revocation
            
        Returns:
            bool: True if email sent successfully
        """
        try:
            # This would need customer email lookup in production
            # For now, log the revocation
            logger.info(f"License revocation notification: {license_key} (reason: {reason})")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send revocation notification: {e}")
            return False