from django.core.mail.backends.smtp import EmailBackend as DjangoEmailBackend
import smtplib
import ssl
import uuid
import socket
from email.utils import formatdate, make_msgid
from email.message import EmailMessage

class SSLUnverifiedEmailBackend(DjangoEmailBackend):
    """
    Custom email backend that:
    1. Disables SSL certificate verification
    2. Adds required headers for Gmail compliance
    """
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Disable SSL certificate verification
        self.ssl_context = ssl._create_unverified_context()
    
    def open(self):
        """Open a connection to the SMTP server with SSL verification disabled"""
        if self.connection:
            return False
        
        connection_class = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
        kwargs = {}
        
        if self.use_ssl:
            # Pass our unverified SSL context
            kwargs['context'] = self.ssl_context
        
        self.connection = connection_class(self.host, self.port, **kwargs)
        
        if not self.use_ssl and self.use_tls:
            # Pass our unverified SSL context for STARTTLS
            self.connection.starttls(context=self.ssl_context)
        
        if self.username and self.password:
            self.connection.login(self.username, self.password)
        
        return True
    
    def _send(self, email_message):
        """Add required headers before sending"""
        # Add Message-ID header if missing (required by Gmail)
        if 'Message-ID' not in email_message.extra_headers:
            email_message.extra_headers['Message-ID'] = make_msgid(domain=self.host)
        
        # Add Date header if missing
        if 'Date' not in email_message.extra_headers:
            email_message.extra_headers['Date'] = formatdate(localtime=True)
            
        return super()._send(email_message)
