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.conf import settings

from alumni.models import Alumni

# If using SMS
import requests


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:
            # --- SMS NOTIFICATION ---
            sms_api_key = settings.MNOTIFY_API_KEY
            sms_endpoint = 'https://api.mnotify.com/api/sms/quick'

            if alumni.contact_number:
                data = {
                    # "recipient": ['0545079851'],
                    "recipient": [alumni.contact_number],
                    "sender": settings.MNOTIFY_SENDER_ID,
                    "message": f"Dear {alumni.full_name},Your profile is incomplete. Please update:Academic History and Employment Details. Thank you. LOGIN HERE: http://alumni.ubids.edu.gh/",
                    "is_schedule": False,
                    "schedule_date": ""
                }
                response = requests.post(f"{sms_endpoint}?key={sms_api_key}", json=data)
                if response.status_code == 200:
                    self.stdout.write(f"SMS sent to {alumni.contact_number}")
                else:
                    self.stdout.write(f"Failed to send SMS to {alumni.contact_number}: {response.text}")


        self.stdout.write(self.style.SUCCESS("Notifications sent successfully"))