import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from tenacity import retry, stop_after_attempt, wait_exponential
from app.channels.base import NotificationChannel, DeliveryResult
from app.core.config import get_settings

settings = get_settings()


class EmailAdapter(NotificationChannel):
    """SMTP email adapter (Mailgun/SendGrid compatible)"""
    
    @property
    def channel_name(self) -> str:
        return "email"
    
    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=2, max=10)
    )
    async def send(self, target: str, content: str, **kwargs) -> DeliveryResult:
        """
        Send email via SMTP
        
        Args:
            target: recipient email address
            content: email body (plain text or HTML)
            kwargs: subject (default: "Notification"), html (bool), from_email, reply_to
        
        Requires env vars: SMTP_HOST, SMTP_PORT, EMAIL_FROM
        Optional: SMTP_USER, SMTP_PASSWORD, EMAIL_REPLY_TO
        """
        if not settings.SMTP_HOST:
            return DeliveryResult(
                success=False,
                error="SMTP_HOST not configured"
            )
        
        subject = kwargs.get("subject", "Notification")
        is_html = kwargs.get("html", False)
        from_email = kwargs.get("from_email", settings.EMAIL_FROM)
        reply_to = kwargs.get("reply_to", settings.EMAIL_REPLY_TO)
        
        msg = MIMEMultipart("alternative") if is_html else MIMEText(content, "plain", "utf-8")
        
        if is_html:
            msg.attach(MIMEText(content, "plain", "utf-8"))
            msg.attach(MIMEText(content, "html", "utf-8"))
        
        msg["Subject"] = subject
        msg["From"] = from_email
        msg["To"] = target
        if reply_to:
            msg["Reply-To"] = reply_to
        
        try:
            with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=30) as server:
                if settings.SMTP_USER and settings.SMTP_PASSWORD:
                    server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
                
                server.send_message(msg)
            
            return DeliveryResult(
                success=True,
                message_id=msg["Message-ID"] if "Message-ID" in msg else None,
                response_meta={"to": target, "subject": subject}
            )
        
        except smtplib.SMTPException as e:
            return DeliveryResult(
                success=False,
                error=f"SMTP error: {str(e)}"
            )
        except Exception as e:
            return DeliveryResult(
                success=False,
                error=f"Unexpected error: {str(e)}"
            )





























