# aiva/email/sender.py
import time
import random
import logging
from aiva.monitoring import increment_email_retry_count

logger = logging.getLogger(__name__)

class EmailSender:
    def __init__(self, max_retries=3):
        self.max_retries = max_retries

    def send_email(self, to, subject, body):
        retries = 0
        while retries < self.max_retries:
            try:
                self._attempt_send(to, subject, body)
                return True  # Email sent successfully
            except Exception as e:
                retries += 1
                increment_email_retry_count()
                logger.error(f"Email send failed (attempt {retries}/{self.max_retries}): {e}")
                time.sleep(2**retries)  # Exponential backoff

        # If all retries failed, push to DLQ (simulated here)
        self.push_to_dlq(to, subject, body)
        return False  # Email failed to send after all retries

    def _attempt_send(self, to, subject, body):
        # Simulate email sending (replace with actual email sending logic)
        if random.random() < 0.8:  # Simulate occasional failures
            logger.info(f"Sending email to {to} with subject '{subject}'")
            print(f"Sending email to {to} with subject '{subject}' (Simulated)")  # Replace with actual sending
            return
        else:
            raise Exception("Simulated email sending error")

    def push_to_dlq(self, to, subject, body):
        # Simulate pushing to a dead-letter queue (replace with actual DLQ logic)
        from aiva.monitoring import increment_dlq_size
        increment_dlq_size()
        logger.warning(f"Pushing email to DLQ: to={to}, subject='{subject}', body='{body}'")
        print(f"Email pushed to DLQ: to={to}, subject='{subject}' (Simulated)")  # Replace with actual DLQ push