from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
import traceback

class Command(BaseCommand):
    help = 'Send a test email to a specified user (synchronous)'

    def add_arguments(self, parser):
        parser.add_argument('email', type=str, help='The email address to send the test to')

    def handle(self, *args, **options):
        email = options['email']
        User = get_user_model()

        try:
            user = User.objects.filter(email=email).first()
            if not user:
                class DummyUser:
                    pass
                user = DummyUser()
                user.first_name = "Test User"
                user.email = email

            self.stdout.write(f"Sending test email to {email}...")

            context = {'user': user, 'code': '123456'}
            html_content = render_to_string('emails/verify_account.html', context)
            text_content = strip_tags(html_content)

            send_mail(
                "Test Email from FaceLook - Synchronous Check",
                text_content,
                settings.DEFAULT_FROM_EMAIL,
                [email],
                html_message=html_content,
                fail_silently=False,
            )

            self.stdout.write(self.style.SUCCESS('Email sent successfully! Connection is valid.'))

        except Exception as e:
            traceback.print_exc()
            self.stdout.write(self.style.ERROR(f'Failed to send email: {str(e)}'))
