import logging
import smtplib
from email.message import EmailMessage

from flask import current_app

logger = logging.getLogger(__name__)


def send_email_message(to_email: str, subject: str, body: str) -> bool:
    host = current_app.config.get("SMTP_HOST", "")
    port = int(current_app.config.get("SMTP_PORT", 587))
    username = current_app.config.get("SMTP_USERNAME", "")
    password = current_app.config.get("SMTP_PASSWORD", "")
    use_tls = current_app.config.get("SMTP_USE_TLS", False)
    use_ssl = current_app.config.get("SMTP_USE_SSL", port == 465)
    mail_from = current_app.config.get("MAIL_FROM", "noreply@swiftcart.com")
    dev_log = current_app.config.get("REGISTRATION_OTP_DEV_LOG", False)

    if not host:
        if dev_log:
            logger.warning("SMTP not configured. Email OTP for %s: %s", to_email, body)
            print(f"[SwiftCart OTP] Email to {to_email}: {body}")
            return True
        return False

    message = EmailMessage()
    message["Subject"] = subject
    message["From"] = mail_from
    message["To"] = to_email
    message.set_content(body)

    try:
        if use_ssl:
            with smtplib.SMTP_SSL(host, port, timeout=20) as smtp:
                if username and password:
                    smtp.login(username, password)
                smtp.send_message(message)
        else:
            with smtplib.SMTP(host, port, timeout=20) as smtp:
                if use_tls:
                    smtp.starttls()
                if username and password:
                    smtp.login(username, password)
                smtp.send_message(message)
        return True
    except Exception as exc:
        logger.exception("Failed to send email OTP to %s: %s", to_email, exc)
        if dev_log:
            print(f"[SwiftCart OTP] Email delivery failed; code logged for {to_email}: {body}")
            return True
        return False
