"""
Système de notifications pour ECOLUX Dashboard
"""
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from userapp.models import CostumUser


def send_project_notifications(project, action):
    """Envoyer des notifications pour les actions sur les projets"""
    try:
        # Préparer la liste des destinataires
        recipients = []
        
        # Client
        if project.client and project.client.user.email:
            recipients.append({
                'email': project.client.user.email,
                'name': project.client.user.get_full_name() or project.client.user.username,
                'role': 'Client'
            })
        
        # DRH (tous)
        drh_users = CostumUser.objects.filter(type='DRH').select_related('user')
        for drh in drh_users:
            if drh.user.email:
                recipients.append({
                    'email': drh.user.email,
                    'name': drh.user.get_full_name() or drh.user.username,
                    'role': 'DRH'
                })
        
        # Techniciens assignés
        for tech in project.assigned_technicians.all():
            if tech.user.email:
                recipients.append({
                    'email': tech.user.email,
                    'name': tech.user.get_full_name() or tech.user.username,
                    'role': 'Technicien'
                })
        
        # Personnaliser le message selon l'action
        if action == 'created':
            subject = f"🏗️ Nouveau projet créé : {project.title}"
        elif action == 'updated':
            subject = f"🔄 Projet modifié : {project.title}"
        else:
            return
        
        # Envoyer les emails
        for recipient in recipients:
            try:
                budget_text = f"{project.budget:,.0f} FCFA" if project.budget else "Non défini"
                
                message = f"""
Bonjour {recipient['name']},

Le projet "{project.title}" a été {action}.

📋 Détails du projet:
• Client: {project.client.user.get_full_name()}
• Statut: {project.get_status_display()}
• Budget: {budget_text}
• Date de début: {project.start_date.strftime('%d/%m/%Y') if project.start_date else 'Non définie'}
• Date de fin prévue: {project.end_date.strftime('%d/%m/%Y') if project.end_date else 'Non définie'}

👥 Techniciens assignés: {', '.join([t.user.get_full_name() for t in project.assigned_technicians.all()]) if project.assigned_technicians.exists() else 'Aucun'}

📝 Description:
{project.description[:200]}...

Cordialement,
L'équipe ECOLUX
                """
                
                send_mail(
                    subject=subject,
                    message=message,
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[recipient['email']],
                    fail_silently=True,
                )
            except Exception as e:
                print(f"Erreur envoi email à {recipient['email']}: {str(e)}")
                
    except Exception as e:
        print(f"Erreur dans send_project_notifications: {str(e)}")


def send_activity_notifications(activity, action):
    """Envoyer des notifications pour les actions sur les activités"""
    try:
        # Préparer la liste des destinataires
        recipients = []
        
        # Client du projet
        if activity.project.client and activity.project.client.user.email:
            recipients.append({
                'email': activity.project.client.user.email,
                'name': activity.project.client.user.get_full_name() or activity.project.client.user.username,
                'role': 'Client'
            })
        
        # DRH (tous)
        drh_users = CostumUser.objects.filter(type='DRH').select_related('user')
        for drh in drh_users:
            if drh.user.email:
                recipients.append({
                    'email': drh.user.email,
                    'name': drh.user.get_full_name() or drh.user.username,
                    'role': 'DRH'
                })
        
        # Technicien assigné à l'activité
        if activity.assigned_to and activity.assigned_to.user.email:
            recipients.append({
                'email': activity.assigned_to.user.email,
                'name': activity.assigned_to.user.get_full_name() or activity.assigned_to.user.username,
                'role': 'Technicien assigné'
            })
        
        # Tous les techniciens assignés au projet
        for tech in activity.project.assigned_technicians.all():
            if tech.user.email and tech.id != (activity.assigned_to.id if activity.assigned_to else None):
                recipients.append({
                    'email': tech.user.email,
                    'name': tech.user.get_full_name() or tech.user.username,
                    'role': 'Technicien du projet'
                })
        
        # Personnaliser le message selon l'action
        if action == 'created':
            subject = f"📋 Nouvelle activité : {activity.title}"
        elif action == 'updated':
            subject = f"🔄 Activité modifiée : {activity.title}"
        else:
            return
        
        # Supprimer les doublons d'emails
        unique_recipients = {}
        for recipient in recipients:
            unique_recipients[recipient['email']] = recipient
        
        # Envoyer les emails
        for recipient in unique_recipients.values():
            try:
                # Compter les fichiers joints
                files_count = (
                    activity.images.count() + 
                    activity.videos.count() + 
                    activity.files.count()
                )
                
                message = f"""
Bonjour {recipient['name']},

Une nouvelle activité a été {action} dans le projet "{activity.project.title}".

📋 Détails de l'activité:
• Titre: {activity.title}
• Type: {activity.get_activity_type_display()}
• Priorité: {activity.get_priority_display()}
• Assigné à: {activity.assigned_to.user.get_full_name() if activity.assigned_to else 'Non assigné'}
• Échéance: {activity.due_date.strftime('%d/%m/%Y') if activity.due_date else 'Non définie'}
• Fichiers joints: {files_count}

📝 Description:
{activity.description[:300]}...

📁 Projet: {activity.project.title}
👤 Client: {activity.project.client.user.get_full_name()}

Cordialement,
L'équipe ECOLUX
                """
                
                send_mail(
                    subject=subject,
                    message=message,
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[recipient['email']],
                    fail_silently=True,
                )
            except Exception as e:
                print(f"Erreur envoi email à {recipient['email']}: {str(e)}")
                
    except Exception as e:
        print(f"Erreur dans send_activity_notifications: {str(e)}")
