"""
NovaLang Email Service - Built-in email sending support
Uses Flask-Mail for SMTP email delivery
"""

from flask_mail import Mail, Message
from typing import List, Optional
import os

class EmailService:
    """Built-in email service for NovaLang applications"""
    
    def __init__(self, app=None):
        self.mail = None
        self.app = app
        if app:
            self.init_app(app)
    
    def init_app(self, app):
        """Initialize email service with Flask app"""
        # Configure from environment or config
        app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'smtp.gmail.com')
        app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', '587'))
        app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'True').lower() == 'true'
        app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', '')
        app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', '')
        app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', 
                                                       os.getenv('MAIL_USERNAME', ''))
        
        self.mail = Mail(app)
        self.app = app
    
    def send_email(self, 
                   to: List[str], 
                   subject: str, 
                   body: str,
                   html: Optional[str] = None,
                   sender: Optional[str] = None) -> bool:
        """
        Send an email
        
        Args:
            to: List of recipient email addresses
            subject: Email subject line
            body: Plain text email body
            html: Optional HTML email body
            sender: Optional sender email (defaults to MAIL_DEFAULT_SENDER)
        
        Returns:
            bool: True if sent successfully, False otherwise
        
        Example:
            email_service.send_email(
                to=['user@example.com'],
                subject='Welcome to NovaLang!',
                body='Thank you for signing up.'
            )
        """
        try:
            msg = Message(
                subject=subject,
                recipients=to,
                body=body,
                html=html,
                sender=sender
            )
            self.mail.send(msg)
            return True
        except Exception as e:
            print(f"❌ Email send failed: {e}")
            return False
    
    def send_template_email(self,
                           to: List[str],
                           subject: str,
                           template_name: str,
                           **kwargs) -> bool:
        """
        Send email using a template
        
        Args:
            to: List of recipient email addresses
            subject: Email subject line
            template_name: Name of template (e.g., 'welcome', 'reset_password')
            **kwargs: Template variables
        
        Returns:
            bool: True if sent successfully
        
        Example:
            email_service.send_template_email(
                to=['user@example.com'],
                subject='Welcome!',
                template_name='welcome',
                username='john_doe',
                activation_link='https://...'
            )
        """
        # Common email templates
        templates = {
            'welcome': """
                <h1>Welcome to {app_name}!</h1>
                <p>Hi {username},</p>
                <p>Thank you for signing up. We're excited to have you on board!</p>
                <p>Get started by exploring our features.</p>
                <p>Best regards,<br>The {app_name} Team</p>
            """,
            'reset_password': """
                <h1>Password Reset Request</h1>
                <p>Hi {username},</p>
                <p>You requested to reset your password. Click the link below:</p>
                <p><a href="{reset_link}">Reset Password</a></p>
                <p>This link expires in {expiry_hours} hours.</p>
                <p>If you didn't request this, please ignore this email.</p>
            """,
            'verification': """
                <h1>Verify Your Email</h1>
                <p>Hi {username},</p>
                <p>Please verify your email address by clicking:</p>
                <p><a href="{verification_link}">Verify Email</a></p>
                <p>This link expires in {expiry_hours} hours.</p>
            """,
            'order_confirmation': """
                <h1>Order Confirmation</h1>
                <p>Hi {username},</p>
                <p>Your order #{order_id} has been confirmed!</p>
                <p><strong>Total:</strong> ${total}</p>
                <p>We'll send you another email when your order ships.</p>
                <p>Thank you for your purchase!</p>
            """
        }
        
        # Get template and format with variables
        template = templates.get(template_name, '<p>{body}</p>')
        html_body = template.format(**kwargs)
        
        # Create plain text version
        import re
        text_body = re.sub('<[^<]+?>', '', html_body)  # Strip HTML tags
        
        return self.send_email(to, subject, text_body, html_body)


# Singleton instance
_email_service = None

def get_email_service():
    """Get the global email service instance"""
    global _email_service
    return _email_service

def init_email_service(app):
    """Initialize the global email service"""
    global _email_service
    _email_service = EmailService(app)
    return _email_service
