# from django.core.management.base import BaseCommand
# from django.db.models import Count, Q
# from django.utils.timezone import now, timedelta
# from django.core.mail import send_mail
# from django.template.loader import render_to_string
# from django.conf import settings

# from alumni.models import Alumni


# class Command(BaseCommand):
#     help = "Send weekly reminders to alumni with incomplete profiles"

#     def handle(self, *args, **kwargs):

#         alumni_list = Alumni.objects.annotate(
#             academic_count=Count('academic_records'),
#             employment_count=Count('employment_records')
#         ).filter(
#             Q(academic_count=0) | Q(employment_count=0)
#         ).distinct()

       
#         for alumni in alumni_list:

#             # EMAIL
#             if alumni.user.email:
#                 subject = "Complete Your Alumni Profile"
#                 message = render_to_string("alumni/incomplete_profile_notification_email.html", {
#                     "alumni": alumni,
#                 })
                
#                 send_mail(
#                     subject,
#                     message,
#                     settings.DEFAULT_FROM_EMAIL,
#                     [alumni.user.email],
#                     html_message=message,
#                     fail_silently=False
#                 )
#                 self.stdout.write(f"Email sent to {alumni.user.email}")
            

#         self.stdout.write(self.style.SUCCESS("Notifications sent successfully"))



from django.core.management.base import BaseCommand
from django.db.models import Count, Q
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from django.core.validators import validate_email
from django.core.exceptions import ValidationError

from alumni.models import Alumni


class Command(BaseCommand):
    help = "Send weekly reminders to alumni with incomplete profiles"

    def handle(self, *args, **kwargs):

        alumni_list = Alumni.objects.annotate(
            academic_count=Count('academic_records'),
            employment_count=Count('employment_records')
        ).filter(
            Q(academic_count=0) | Q(employment_count=0)
        ).distinct()

        for alumni in alumni_list:

            email = alumni.user.email if alumni.user else None

            # VALIDATE EMAIL
            if not email:
                self.stdout.write(f"Skipping {alumni.full_name}: No email")
                continue

            try:
                validate_email(email)
            except ValidationError:
                self.stdout.write(f"Skipping {alumni.full_name}: Invalid email ({email})")
                continue

            # EMAIL TEMPLATE
            subject = "Complete Your Alumni Profile"

            message = render_to_string(
                "alumni/incomplete_profile_notification_email.html",
                {"alumni": alumni}
            )

            # SEND EMAIL
            try:
                send_mail(
                    subject=subject,
                    message="Please enable HTML to view this email.",
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[email],
                    html_message=message,
                    fail_silently=False
                )

                self.stdout.write(f"Email sent to {email}")

            except Exception as e:
                self.stdout.write(f"Failed to send to {email}: {e}")

        self.stdout.write(self.style.SUCCESS("Notifications completed"))