import os
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
from core.tokens import account_activation_token

User = get_user_model()

class Command(BaseCommand):
    help = 'Resend activation email to a specific user'

    def add_arguments(self, parser):
        parser.add_argument('username', type=str)
        parser.add_argument('--domain', type=str, default=os.getenv("HOST_FQDN", "localhost:8000"))

    def handle(self, *args, **args_options):
        username = args_options['username']
        domain = args_options['domain']
        
        try:
            user = User.objects.get(username=username)
            if user.is_active:
                self.stdout.write(self.style.WARNING(f"User '{username}' is already active."))
                return

            mail_subject = 'Activate your Referral Rewards account.'
            message = render_to_string('core/emails/activation_email.html', {
                'user': user,
                'domain': domain,
                'protocol': 'https', # Defaulting to https for Flatlogic
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            
            email = EmailMessage(
                mail_subject, message, to=[user.email]
            )
            email.send()
            self.stdout.write(self.style.SUCCESS(f"Successfully sent activation email to '{username}' ({user.email})."))
            
        except User.DoesNotExist:
            self.stdout.write(self.style.ERROR(f"User '{username}' does not exist."))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error sending email: {str(e)}"))
