# aiva/core/smtp_client.py

import smtplib
import ssl
import logging
from aiva.config.config_manager import ConfigManager  # Assuming ConfigManager exists

logger = logging.getLogger(__name__)

class SMTPClient:
    def __init__(self, config_manager: ConfigManager):
        self.config = config_manager.get_smtp_config()
        self.context = None
        self.create_ssl_context()

    def create_ssl_context(self):
        self.context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)

        if self.config.get('ca_certs'):
            try:
                self.context.load_verify_locations(cafile=self.config['ca_certs'])
            except FileNotFoundError:
                logger.warning(f"CA certificate file not found: {self.config['ca_certs']}. Falling back to system default CAs.")
            except Exception as e:
                logger.error(f"Error loading CA certificate file: {self.config['ca_certs']}. Falling back to system default CAs. Error: {e}")

        if self.config.get('pinned_certs'):
             # Example: {'example.com': '/path/to/cert.pem', 'another.com': '/path/to/cert2.pem'}
            for hostname, cert_path in self.config['pinned_certs'].items():
                try:
                    # Placeholder for actual certificate pinning logic.
                    # In a real implementation, you'd verify the server's certificate
                    # against the certificate at cert_path during the TLS handshake.
                    # This is a simplified example.
                    with open(cert_path, 'r') as f:
                        cert_data = f.read()
                    # In a real implementation, you'd store the cert_data (or its hash)
                    # and use it during the connection to verify the server's certificate.
                    logger.info(f"Loaded pinned certificate for {hostname} from {cert_path}")

                except FileNotFoundError:
                    logger.warning(f"Pinned certificate file not found for {hostname}: {cert_path}. Disabling certificate pinning for this server.")
                    # Consider removing the hostname from the pinned_certs config or setting a flag
                    # to avoid retrying on subsequent connections.
                    # For simplicity, we'll just log the warning.
                except Exception as e:
                    logger.error(f"Error loading pinned certificate for {hostname} from {cert_path}. Disabling certificate pinning for this server. Error: {e}")

    def send_email(self, recipient, subject, body):
        try:
            with smtplib.SMTP(self.config['server'], self.config['port']) as server:
                server.starttls(context=self.context)
                server.login(self.config['username'], self.config['password'])
                message = f"Subject: {subject}\n\n{body}"
                server.sendmail(self.config['username'], recipient, message)
            logger.info(f"Email sent successfully to {recipient}")
        except Exception as e:
            logger.error(f"Failed to send email to {recipient}: {e}")


if __name__ == '__main__':
    # Example Usage (Requires a valid configuration file)
    # This is just placeholder and needs to be properly integrated with AIVA's architecture
    class MockConfigManager:
        def get_smtp_config(self):
            return {
                'server': 'smtp.example.com',
                'port': 587,
                'username': 'user@example.com',
                'password': 'password',
                'ca_certs': 'path/to/nonexistent/ca_certs.pem',
                'pinned_certs': {
                    'example.com': 'path/to/nonexistent/pinned_cert.pem'
                }
            }
    
    config_manager = MockConfigManager()
    smtp_client = SMTPClient(config_manager)
    smtp_client.send_email('test@example.com', 'Test Email', 'This is a test email.')