
import os
from django.core.management.base import BaseCommand
from django.conf import settings
from notifications.email_service import EmailService
from settings.models import SystemSettings

class Command(BaseCommand):
    help = 'Check email configuration in production environment'

    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            type=str,
            help='Test email address',
            required=True
        )

    def handle(self, *args, **options):
        test_email = options['email']
        
        self.stdout.write(self.style.SUCCESS('=== Production Email Check ==='))
        
        # Check environment variables
        self.stdout.write("\n📧 Environment Variables:")
        env_vars = ['EMAIL_HOST', 'EMAIL_HOST_USER', 'EMAIL_HOST_PASSWORD', 'EMAIL_PORT']
        all_set = True
        
        for var in env_vars:
            value = os.environ.get(var)
            if var == 'EMAIL_HOST_PASSWORD':
                display_value = '✅ Set' if value else '❌ Missing'
            else:
                display_value = value if value else '❌ Missing'
            
            self.stdout.write(f"  {var}: {display_value}")
            if not value:
                all_set = False
        
        if not all_set:
            self.stdout.write(self.style.ERROR('\n❌ Missing environment variables!'))
            self.stdout.write('Set these in Replit Secrets and restart your application.')
            return
        
        # Test email sending
        self.stdout.write(f"\n📤 Testing email to {test_email}...")
        
        try:
            email_service = EmailService()
            success, error_msg = email_service.send_test_email(test_email)
            
            if success:
                self.stdout.write(self.style.SUCCESS('✅ Email sent successfully!'))
                self.stdout.write('Check your email inbox (and spam folder).')
            else:
                self.stdout.write(self.style.ERROR(f'❌ Email failed: {error_msg}'))
                
                # Provide specific help based on error
                if 'Authentication' in error_msg:
                    self.stdout.write('\n🔐 Authentication Error Help:')
                    self.stdout.write('- For Gmail: Use App Password, not regular password')
                    self.stdout.write('- Enable 2FA and generate App Password')
                elif 'Connection' in error_msg:
                    self.stdout.write('\n🌐 Connection Error Help:')
                    self.stdout.write('- Check EMAIL_HOST and EMAIL_PORT')
                    self.stdout.write('- Ensure firewall allows SMTP traffic')
                    
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'❌ Unexpected error: {str(e)}'))
