"""
Custom email backend that handles localhost SSL certificate issues.
Disables SSL certificate verification for localhost connections.
"""
import ssl
from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings
import logging

logger = logging.getLogger(__name__)


class LocalhostSMTPBackend(EmailBackend):
    """
    Custom SMTP backend that disables SSL certificate verification
    for localhost connections. This is safe for localhost mail servers.
    """
    
    def open(self):
        """
        Override to create SSL context without certificate verification
        when connecting to localhost.
        """
        if self.use_ssl or self.use_tls:
            # Check if connecting to localhost
            if self.host in ['localhost', '127.0.0.1', '::1']:
                # Create SSL context without certificate verification for localhost
                self.connection = None
                try:
                    import smtplib
                    
                    if self.use_ssl:
                        # For SSL connections
                        context = ssl.create_default_context()
                        context.check_hostname = False
                        context.verify_mode = ssl.CERT_NONE
                        # SMTP_SSL uses 'context' parameter (Python 3.3+)
                        import sys
                        if sys.version_info >= (3, 3):
                            self.connection = smtplib.SMTP_SSL(
                                self.host,
                                self.port,
                                timeout=self.timeout,
                                context=context
                            )
                        else:
                            # For older Python, use unverified context
                            self.connection = smtplib.SMTP_SSL(
                                self.host,
                                self.port,
                                timeout=self.timeout
                            )
                    else:
                        # For TLS connections
                        self.connection = smtplib.SMTP(
                            self.host,
                            self.port,
                            timeout=self.timeout
                        )
                        # Create SSL context without certificate verification
                        context = ssl.create_default_context()
                        context.check_hostname = False
                        context.verify_mode = ssl.CERT_NONE
                        # Use context parameter (Python 3.4+ uses 'context', not 'ssl_context')
                        # For older versions, we'll need to patch the socket after starttls
                        import sys
                        if sys.version_info >= (3, 4):
                            # Python 3.4+ supports context parameter
                            self.connection.starttls(context=context)
                        else:
                            # For older Python, disable verification globally for this connection
                            # by monkey-patching ssl._create_default_https_context temporarily
                            original_context = ssl._create_default_https_context
                            ssl._create_default_https_context = ssl._create_unverified_context
                            try:
                                self.connection.starttls()
                            finally:
                                ssl._create_default_https_context = original_context
                    
                    if self.username and self.password:
                        self.connection.login(self.username, self.password)
                    
                    logger.info(f"Successfully connected to localhost mail server at {self.host}:{self.port}")
                    return True
                    
                except Exception as e:
                    logger.error(f"Failed to connect to localhost mail server: {str(e)}")
                    if self.connection:
                        try:
                            self.connection.quit()
                        except:
                            pass
                        self.connection = None
                    raise
            else:
                # For non-localhost, use standard SSL/TLS with certificate verification
                return super().open()
        else:
            # No SSL/TLS, use standard connection
            return super().open()

