"""
Service d'envoi d'emails pour les notifications de licence
"""
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Optional
import logging

logger = logging.getLogger(__name__)


class EmailService:
    """Service d'envoi d'emails via SMTP"""
    
    def __init__(self):
        """Initialise le service email avec les variables d'environnement"""
        self.smtp_host = os.getenv('SMTP_HOST', 'smtp.gmail.com')
        self.smtp_port = int(os.getenv('SMTP_PORT', '587'))
        self.smtp_use_ssl = os.getenv('SMTP_USE_SSL', 'False').lower() == 'true'
        self.smtp_user = os.getenv('SMTP_USER', '')
        self.smtp_password = os.getenv('SMTP_PASSWORD', '')
        self.from_email = os.getenv('FROM_EMAIL', self.smtp_user)
        self.from_name = os.getenv('FROM_NAME', 'Web Sentinel')
        
        # Mode debug : si pas de config SMTP, on logue seulement
        self.debug_mode = not (self.smtp_user and self.smtp_password)
        
        if self.debug_mode:
            logger.warning("⚠️  Mode email DEBUG activé (pas de configuration SMTP)")
    
    def send_license_email(
        self,
        to_email: str,
        api_key: str,
        tier: str,
        customer_name: Optional[str] = None
    ) -> bool:
        """
        Envoie l'email de bienvenue avec la clé API
        
        Args:
            to_email: Email du destinataire
            api_key: Clé API générée
            tier: Niveau d'abonnement
            customer_name: Nom du client (optionnel)
            
        Returns:
            True si envoi réussi, False sinon
        """
        subject = f"🎉 Bienvenue sur Web Sentinel {tier.upper()} - Votre clé API"
        
        # Corps de l'email en HTML
        html_body = self._generate_license_email_html(
            api_key=api_key,
            tier=tier,
            customer_name=customer_name or to_email.split('@')[0]
        )
        
        # Corps de l'email en texte brut (fallback)
        text_body = self._generate_license_email_text(
            api_key=api_key,
            tier=tier,
            customer_name=customer_name or to_email.split('@')[0]
        )
        
        return self._send_email(
            to_email=to_email,
            subject=subject,
            html_body=html_body,
            text_body=text_body
        )
    
    def _generate_license_email_html(
        self,
        api_key: str,
        tier: str,
        customer_name: str
    ) -> str:
        """Génère le corps HTML de l'email de licence"""
        
        tier_features = {
            'STARTER': [
                '✅ 10 domaines maximum',
                '✅ Scans de sécurité complets',
                '✅ Rapports HTML/JSON',
                '✅ Support email'
            ],
            'PRO': [
                '✅ 50 domaines maximum',
                '✅ Scans de sécurité avancés',
                '✅ Tests invasifs autorisés',
                '✅ Rapports détaillés avec historique',
                '✅ API REST complète',
                '✅ Support prioritaire'
            ],
            'ENTERPRISE': [
                '✅ Domaines illimités',
                '✅ Scans de sécurité avancés',
                '✅ Tests invasifs autorisés',
                '✅ Multi-utilisateurs (10 utilisateurs)',
                '✅ API REST complète',
                '✅ Intégration CI/CD',
                '✅ Support 24/7 dédié',
                '✅ Fonctionnalités personnalisées'
            ]
        }
        
        features = tier_features.get(tier.upper(), tier_features['STARTER'])
        features_html = ''.join([f'<li style="margin: 8px 0;">{f}</li>' for f in features])
        
        return f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background-color: #f5f5f5;">
    <div style="max-width: 600px; margin: 40px auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        
        <!-- Header -->
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center;">
            <h1 style="color: white; margin: 0; font-size: 28px;">🎉 Bienvenue sur Web Sentinel !</h1>
            <p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0; font-size: 16px;">Votre abonnement {tier.upper()} est maintenant actif</p>
        </div>
        
        <!-- Content -->
        <div style="padding: 40px 30px;">
            <p style="font-size: 16px; color: #333; margin: 0 0 20px 0;">Bonjour {customer_name},</p>
            
            <p style="font-size: 16px; color: #333; line-height: 1.6; margin: 0 0 30px 0;">
                Merci d'avoir souscrit à Web Sentinel {tier.upper()} ! Votre compte est maintenant actif et prêt à l'emploi.
            </p>
            
            <!-- API Key Box -->
            <div style="background: #f8f9fa; border: 2px solid #667eea; border-radius: 8px; padding: 20px; margin: 0 0 30px 0;">
                <h3 style="margin: 0 0 10px 0; color: #333; font-size: 18px;">🔑 Votre clé API</h3>
                <code style="display: block; background: white; padding: 15px; border-radius: 6px; font-size: 14px; color: #667eea; word-break: break-all; border: 1px solid #e0e0e0;">
                    {api_key}
                </code>
                <p style="margin: 10px 0 0 0; font-size: 13px; color: #666;">
                    ⚠️ Gardez cette clé secrète et ne la partagez jamais
                </p>
            </div>
            
            <!-- Quick Start -->
            <h3 style="color: #333; font-size: 18px; margin: 0 0 15px 0;">🚀 Démarrage rapide</h3>
            
            <div style="background: #f8f9fa; border-left: 4px solid #667eea; padding: 15px; margin: 0 0 20px 0; border-radius: 4px;">
                <p style="margin: 0 0 10px 0; font-weight: bold; color: #333;">Installation :</p>
                <code style="display: block; background: #2d3748; color: #e2e8f0; padding: 12px; border-radius: 6px; font-size: 13px; margin: 5px 0;">
                    pip install web-sentinel
                </code>
                
                <p style="margin: 15px 0 10px 0; font-weight: bold; color: #333;">Utilisation :</p>
                <code style="display: block; background: #2d3748; color: #e2e8f0; padding: 12px; border-radius: 6px; font-size: 13px; margin: 5px 0;">
                    web-sentinel scan example.com --api-key {api_key[:20]}...
                </code>
                
                <p style="margin: 15px 0 10px 0; font-weight: bold; color: #333;">Ou configurez la clé globalement :</p>
                <code style="display: block; background: #2d3748; color: #e2e8f0; padding: 12px; border-radius: 6px; font-size: 13px; margin: 5px 0;">
                    export WEB_SENTINEL_API_KEY={api_key[:20]}...
                </code>
            </div>
            
            <!-- Features -->
            <h3 style="color: #333; font-size: 18px; margin: 0 0 15px 0;">✨ Vos fonctionnalités {tier.upper()}</h3>
            <ul style="list-style: none; padding: 0; margin: 0 0 30px 0; color: #333; line-height: 1.8;">
                {features_html}
            </ul>
            
            <!-- Support -->
            <div style="background: #e8f4fd; border-radius: 8px; padding: 20px; margin: 0 0 20px 0;">
                <h3 style="margin: 0 0 10px 0; color: #0066cc; font-size: 16px;">💬 Besoin d'aide ?</h3>
                <p style="margin: 0; color: #333; font-size: 14px; line-height: 1.6;">
                    Notre équipe support est disponible :<br>
                    📧 Email : <a href="mailto:support@web-sentinel.com" style="color: #667eea; text-decoration: none;">support@web-sentinel.com</a><br>
                    📚 Documentation : <a href="https://docs.web-sentinel.com" style="color: #667eea; text-decoration: none;">docs.web-sentinel.com</a>
                </p>
            </div>
            
            <p style="font-size: 14px; color: #666; margin: 20px 0 0 0; line-height: 1.6;">
                Merci de votre confiance,<br>
                <strong>L'équipe Web Sentinel</strong>
            </p>
        </div>
        
        <!-- Footer -->
        <div style="background: #f8f9fa; padding: 20px 30px; text-align: center; border-top: 1px solid #e0e0e0;">
            <p style="margin: 0; font-size: 12px; color: #999;">
                © 2025 Web Sentinel - Tous droits réservés<br>
                Cet email contient des informations confidentielles
            </p>
        </div>
    </div>
</body>
</html>
"""
    
    def _generate_license_email_text(
        self,
        api_key: str,
        tier: str,
        customer_name: str
    ) -> str:
        """Génère le corps texte brut de l'email de licence"""
        return f"""
🎉 Bienvenue sur Web Sentinel {tier.upper()} !

Bonjour {customer_name},

Merci d'avoir souscrit à Web Sentinel {tier.upper()} ! Votre compte est maintenant actif.

🔑 VOTRE CLÉ API :
{api_key}

⚠️  Gardez cette clé secrète et ne la partagez jamais.

🚀 DÉMARRAGE RAPIDE :

Installation :
  pip install web-sentinel

Utilisation :
  web-sentinel scan example.com --api-key {api_key}

Ou configurez la clé globalement :
  export WEB_SENTINEL_API_KEY={api_key}

💬 BESOIN D'AIDE ?
- Email : support@web-sentinel.com
- Documentation : https://docs.web-sentinel.com

Merci de votre confiance,
L'équipe Web Sentinel

---
© 2025 Web Sentinel - Tous droits réservés
Cet email contient des informations confidentielles
"""
    
    def _send_email(
        self,
        to_email: str,
        subject: str,
        html_body: str,
        text_body: str
    ) -> bool:
        """
        Envoie un email via SMTP
        
        Args:
            to_email: Email du destinataire
            subject: Sujet de l'email
            html_body: Corps HTML
            text_body: Corps texte brut
            
        Returns:
            True si envoi réussi, False sinon
        """
        # Mode debug : on logue seulement
        if self.debug_mode:
            logger.info(f"""
╔══════════════════════════════════════════════════════════════════
║ 📧 EMAIL DEBUG MODE
╠══════════════════════════════════════════════════════════════════
║ To: {to_email}
║ Subject: {subject}
╠══════════════════════════════════════════════════════════════════
{text_body}
╚══════════════════════════════════════════════════════════════════
""")
            return True
        
        # Mode production : envoi réel
        try:
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = f"{self.from_name} <{self.from_email}>"
            msg['To'] = to_email
            
            # Ajouter les deux versions
            part1 = MIMEText(text_body, 'plain', 'utf-8')
            part2 = MIMEText(html_body, 'html', 'utf-8')
            msg.attach(part1)
            msg.attach(part2)
            
            # Connexion SMTP (SSL ou TLS selon configuration)
            if self.smtp_use_ssl:
                # Port 465 : SSL direct
                with smtplib.SMTP_SSL(self.smtp_host, self.smtp_port, timeout=30) as server:
                    server.login(self.smtp_user, self.smtp_password)
                    server.send_message(msg)
            else:
                # Port 587 : TLS (STARTTLS)
                with smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=30) as server:
                    server.starttls()
                    server.login(self.smtp_user, self.smtp_password)
                    server.send_message(msg)
            
            logger.info(f"✅ Email envoyé à {to_email}")
            return True
            
        except Exception as e:
            logger.error(f"❌ Erreur envoi email à {to_email}: {e}")
            return False
    
    def send_subscription_cancelled_email(
        self,
        to_email: str,
        tier: str,
        customer_name: Optional[str] = None
    ) -> bool:
        """
        Envoie un email de confirmation d'annulation
        
        Args:
            to_email: Email du destinataire
            tier: Niveau d'abonnement
            customer_name: Nom du client (optionnel)
            
        Returns:
            True si envoi réussi, False sinon
        """
        subject = f"Confirmation d'annulation - Web Sentinel {tier.upper()}"
        
        html_body = f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body style="font-family: sans-serif; padding: 20px; background-color: #f5f5f5;">
    <div style="max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; padding: 40px;">
        <h1 style="color: #333;">Abonnement annulé</h1>
        <p>Bonjour {customer_name or to_email.split('@')[0]},</p>
        <p>Votre abonnement Web Sentinel {tier.upper()} a été annulé avec succès.</p>
        <p>Vous conservez l'accès à vos fonctionnalités jusqu'à la fin de votre période de facturation en cours.</p>
        <p>Nous espérons vous revoir bientôt !</p>
        <p style="margin-top: 30px;">L'équipe Web Sentinel</p>
    </div>
</body>
</html>
"""
        
        text_body = f"""
Abonnement annulé

Bonjour {customer_name or to_email.split('@')[0]},

Votre abonnement Web Sentinel {tier.upper()} a été annulé avec succès.

Vous conservez l'accès à vos fonctionnalités jusqu'à la fin de votre période de facturation en cours.

Nous espérons vous revoir bientôt !

L'équipe Web Sentinel
"""
        
        return self._send_email(to_email, subject, html_body, text_body)
