# aiva/modules/email/smtp_client.py
import smtplib
import ssl

class SmtpClient:
    def __init__(self, smtp_server, smtp_port, smtp_username, smtp_password, smtp_ssl_enabled, smtp_ssl_verify):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.smtp_username = smtp_username
        self.smtp_password = smtp_password
        self.smtp_ssl_enabled = smtp_ssl_enabled
        self.smtp_ssl_verify = smtp_ssl_verify

    def send_email(self, sender_email, receiver_email, subject, body):
        message = f"""Subject: {subject}

{body}"""

        context = ssl.create_default_context()
        if not self.smtp_ssl_verify:
            context = ssl._create_unverified_context()

        try:
            if self.smtp_ssl_enabled:
                with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context) as server:
                    server.login(self.smtp_username, self.smtp_password)
                    server.sendmail(sender_email, receiver_email, message)
            else:
                with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                    server.starttls(context=context)
                    server.login(self.smtp_username, self.smtp_password)
                    server.sendmail(sender_email, receiver_email, message)

            print("Email sent successfully!")

        except smtplib.SMTPAuthenticationError:
            print("SMTP Authentication Error: Please check your username and password.")
        except ssl.SSLError as e:
            print(f"SSL Error: {e}")
            print("SSL Certificate Verification Failed: This might be due to an invalid or self-signed certificate.  If you have disabled SSL verification, ensure this is intentional.")
        except Exception as e:
            print(f"An error occurred: {e}")


if __name__ == '__main__':
    # Example Usage (Replace with your actual configuration)
    smtp_server = 'your_smtp_server.com'
    smtp_port = 465  # Or 587 for TLS
    smtp_username = 'your_email@example.com'
    smtp_password = 'your_password'
    smtp_ssl_enabled = True
    smtp_ssl_verify = True # Set to False to disable SSL verification (NOT RECOMMENDED FOR PRODUCTION)

    sender_email = 'your_email@example.com'
    receiver_email = 'recipient@example.com'
    subject = 'Test Email'
    body = 'This is a test email sent from the AIVA system.'

    client = SmtpClient(smtp_server, smtp_port, smtp_username, smtp_password, smtp_ssl_enabled, smtp_ssl_verify)
    client.send_email(sender_email, receiver_email, subject, body)
