import smtplib
import ssl
import yaml
import os

class EmailClient:
    def __init__(self, config_path='config/email.yaml'):
        self.config_path = config_path
        self.config = self._load_config()
        self.host = self.config['host']
        self.port = self.config['port']
        self.username = self.config['username']
        self.password = self.config['password']
        self.use_tls = self.config['use_tls']
        self.ca_certificate_path = self.config.get('ca_certificate_path') # Get optional CA path
        self.sender_email = self.config['sender_email']
        self.recipient_email = self.config['recipient_email']

    def _load_config(self):
        try:
            with open(self.config_path, 'r') as f:
                return yaml.safe_load(f)
        except FileNotFoundError:
            print(f"Error: Configuration file not found at {self.config_path}")
            exit(1)
        except yaml.YAMLError as e:
            print(f"Error parsing YAML configuration: {e}")
            exit(1)

    def send_email(self, subject, body):
        message = f"Subject: {subject}\n\n{body}"

        context = ssl.create_default_context()

        if self.ca_certificate_path:
            try:
                context = ssl.create_default_context(cafile=self.ca_certificate_path)
                print(f"Using custom CA certificate bundle: {self.ca_certificate_path}")
            except FileNotFoundError:
                print(f"Error: Custom CA certificate bundle not found at {self.ca_certificate_path}")
                print("Falling back to system default CA certificates.")
                context = ssl.create_default_context()
            except Exception as e:
                print(f"Error loading custom CA certificate bundle: {e}")
                print("Falling back to system default CA certificates.")
                context = ssl.create_default_context()

        try:
            with smtplib.SMTP(self.host, self.port) as server:
                if self.use_tls:
                    server.starttls(context=context)
                server.login(self.username, self.password)
                server.sendmail(self.sender_email, self.recipient_email, message)
            print("Email sent successfully!")
        except Exception as e:
            print(f"Error sending email: {e}")

if __name__ == '__main__':
    # Example usage
    email_client = EmailClient()
    email_client.send_email("Test Email", "This is a test email from AIVA.")