from django.core.management.base import BaseCommand
from django.conf import settings
from notifications.email_service import EmailService
from settings.models import SystemSettings
import smtplib
from email.mime.text import MIMEText

class Command(BaseCommand):
    help = 'Test and verify email configuration'

    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            type=str,
            help='Test email address to send to',
            default='admin@optinet.co.ke'
        )
        parser.add_argument(
            '--fix',
            action='store_true',
            help='Attempt to fix common email configuration issues',
        )

    def handle(self, *args, **options):
        test_email = options['email']
        fix_issues = options['fix']

        self.stdout.write(
            self.style.SUCCESS('=== Email Configuration Diagnostic ===')
        )

        # Check Django settings
        self.stdout.write("\n1. Checking Django Email Settings:")
        self.stdout.write(f"   EMAIL_BACKEND: {getattr(settings, 'EMAIL_BACKEND', 'Not set')}")
        self.stdout.write(f"   EMAIL_HOST: {getattr(settings, 'EMAIL_HOST', 'Not set')}")
        self.stdout.write(f"   EMAIL_PORT: {getattr(settings, 'EMAIL_PORT', 'Not set')}")
        self.stdout.write(f"   EMAIL_USE_TLS: {getattr(settings, 'EMAIL_USE_TLS', 'Not set')}")
        self.stdout.write(f"   EMAIL_HOST_USER: {'Set' if getattr(settings, 'EMAIL_HOST_USER', '') else 'Not set'}")
        self.stdout.write(f"   EMAIL_HOST_PASSWORD: {'Set' if getattr(settings, 'EMAIL_HOST_PASSWORD', '') else 'Not set'}")

        # Check SystemSettings
        self.stdout.write("\n2. Checking SystemSettings Email Configuration:")
        email_settings = SystemSettings.objects.filter(category='email')

        if not email_settings.exists():
            self.stdout.write(self.style.WARNING("   No email settings found in SystemSettings!"))
            if fix_issues:
                self.stdout.write("   Creating default email settings...")
                self._create_default_email_settings()
        else:
            for setting in email_settings:
                if setting.is_sensitive:
                    value = '••••••••' if setting.value else 'Not set'
                else:
                    value = setting.value or 'Not set'
                self.stdout.write(f"   {setting.key}: {value}")

        # Test EmailService
        self.stdout.write("\n3. Testing EmailService:")
        try:
            email_service = EmailService()

            # Test configuration loading
            if email_service.email_settings:
                self.stdout.write(self.style.SUCCESS("   ✓ EmailService initialized successfully"))

                # Validate settings
                valid, error = email_service._validate_settings()
                if valid:
                    self.stdout.write(self.style.SUCCESS("   ✓ Email settings validation passed"))
                else:
                    self.stdout.write(self.style.ERROR(f"   ✗ Email settings validation failed: {error}"))
                    return
            else:
                self.stdout.write(self.style.ERROR("   ✗ EmailService failed to load settings"))
                return

        except Exception as e:
            self.stdout.write(self.style.ERROR(f"   ✗ EmailService initialization failed: {e}"))
            return

        # Test SMTP connection
        self.stdout.write("\n4. Testing SMTP Connection:")
        try:
            host = email_service.email_settings['HOST']
            port = email_service.email_settings['PORT']
            username = email_service.email_settings['HOST_USER']
            password = email_service.email_settings['HOST_PASSWORD']
            use_tls = email_service.email_settings.get('USE_TLS', True)
            use_ssl = email_service.email_settings.get('USE_SSL', False)

            # Test connection
            if use_ssl:
                server = smtplib.SMTP_SSL(host, port)
            elif use_tls:
                server = smtplib.SMTP(host, port)
                server.starttls()
            else:
                server = smtplib.SMTP(host, port)


            server.login(username, password)
            server.quit()

            self.stdout.write(self.style.SUCCESS("   ✓ SMTP connection successful"))

        except smtplib.SMTPAuthenticationError:
            self.stdout.write(self.style.ERROR("   ✗ SMTP Authentication failed - check username/password"))
            return
        except smtplib.SMTPConnectError:
            self.stdout.write(self.style.ERROR(f"   ✗ Cannot connect to SMTP server {host}:{port}"))
            return
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"   ✗ SMTP connection failed: {e}"))
            return

        # Send test email
        self.stdout.write(f"\n5. Sending Test Email to {test_email}:")
        try:
            success, message = email_service.send_test_email(test_email)
            if success:
                self.stdout.write(self.style.SUCCESS(f"   ✓ Test email sent successfully: {message}"))
            else:
                self.stdout.write(self.style.ERROR(f"   ✗ Test email failed: {message}"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"   ✗ Test email failed with exception: {e}"))

        self.stdout.write(self.style.SUCCESS('\n=== Email Configuration Test Complete ==='))

    def _create_default_email_settings(self):
        """Create default email settings in SystemSettings"""
        default_settings = [
            ('email', 'HOST', 'mail.optinet.co.ke', 'SMTP server hostname'),
            ('email', 'PORT', '587', 'SMTP server port (use 587 for TLS, 465 for SSL)'),
            ('email', 'USE_TLS', 'true', 'Use TLS encryption (for port 587)'),
            ('email', 'USE_SSL', 'false', 'Use SSL encryption (for port 465)'),
            ('email', 'HOST_USER', '', 'SMTP username'),
            ('email', 'HOST_PASSWORD', '', 'SMTP password'),
            ('email', 'DEFAULT_FROM_EMAIL', 'noreply@optinet.co.ke', 'Default from email'),
            ('email', 'FROM_EMAIL', 'noreply@optinet.co.ke', 'From email address'),
            ('email', 'TIMEOUT', '30', 'Connection timeout in seconds'),
        ]
        for category, key, value, description in default_settings:
            SystemSettings.objects.get_or_create(
                category=category,
                key=key,
                defaults={
                    'value': value,
                    'description': description,
                    'is_sensitive': key in ['HOST_PASSWORD'],
                    'is_required': key in ['HOST', 'HOST_USER', 'HOST_PASSWORD']
                }
            )

        self.stdout.write(self.style.SUCCESS("   Default email settings created"))