import logging
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage, get_connection
from django.utils import timezone
from accounts.models import EmailJob

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Sends up to 20 pending EmailJob rows. Runs every 5 minutes.'

    def handle(self, *args, **options):
        start_time = timezone.now()
        self.stdout.write(f"[{start_time}] Starting send_email_jobs...")

        pending_jobs = list(EmailJob.objects.filter(status='pending').order_by('created_at')[:20])
        count = 0

        # Try Django 6.x mailers if available; otherwise use standard get_connection() (Django 4.x / 5.x)
        try:
            from django.core.mail import mailers
            connection = mailers.default
        except (ImportError, AttributeError):
            connection = get_connection()

        for job in pending_jobs:
            try:
                job.attempts += 1
                msg = EmailMessage(
                    subject=job.subject,
                    body=job.body_text,
                    to=[job.to_email],
                    connection=connection,
                )
                msg.send(fail_silently=False)
                job.status = 'sent'
                job.sent_at = timezone.now()
                job.last_error = ''
                job.save(update_fields=['status', 'sent_at', 'attempts', 'last_error'])
                count += 1
            except Exception as e:
                job.last_error = str(e)
                if job.attempts >= 3:
                    job.status = 'failed'
                job.save(update_fields=['status', 'attempts', 'last_error'])
                self.stderr.write(f"Failed sending email to {job.to_email}: {e}")

        end_time = timezone.now()
        self.stdout.write(f"[{end_time}] Completed send_email_jobs. Processed {count} emails.")

