import os
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.utils import timezone
from core.models import Task

class Command(BaseCommand):
    help = 'Sends email reminders for tasks that are due today.'

    def handle(self, *args, **options):
        today = timezone.now().date()
        due_tasks = Task.objects.filter(due_date=today, status__in=['DA_FARE', 'IN_SOSPESO'])

        if not due_tasks:
            self.stdout.write(self.style.SUCCESS('No tasks are due today.'))
            return

        recipient_list = os.environ.get('CONTACT_EMAIL_TO', '').split(',')
        if not recipient_list or not recipient_list[0]:
            self.stdout.write(self.style.ERROR('No recipient email configured. Please set CONTACT_EMAIL_TO environment variable.'))
            return

        for task in due_tasks:
            subject = f'Reminder: Task "{task.title}" is due today!'
            message = f'Hello,\n\nThis is a reminder that your task "{task.title}" is due today, {today}.\n\nCategory: {task.get_category_display()}\nStatus: {task.get_status_display()}\n\nThank you!'
            
            try:
                send_mail(
                    subject,
                    message,
                    os.environ.get('DEFAULT_FROM_EMAIL'),
                    recipient_list,
                    fail_silently=False,
                )
                self.stdout.write(self.style.SUCCESS(f'Successfully sent reminder for task: "{task.title}"'))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'Failed to send email for task: "{task.title}". Error: {e}'))
