import smtplib
import ssl
import threading
from email.message import EmailMessage
from email.utils import formataddr, make_msgid

import config


def send_mail(subject, text_body, to=None, reply_to=None, html_body=None, timeout=20):
    """Send an email using the [smtp] section of settings.ini. Raises on failure."""
    s = config.smtp_settings()
    if not s.get("host"):
        raise RuntimeError("SMTP host is not configured")
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = formataddr((s.get("from_name") or "", s.get("from_email") or s.get("username")))
    msg["To"] = to or s.get("recipient") or s.get("from_email")
    msg["Message-ID"] = make_msgid(domain="bandjouncommunitytexas.org")
    if reply_to:
        msg["Reply-To"] = reply_to
    msg.set_content(text_body)
    if html_body:
        msg.add_alternative(html_body, subtype="html")

    port = int(s.get("port") or 587)
    security = (s.get("security") or "starttls").lower()
    ctx = ssl.create_default_context()
    if security == "ssl":
        server = smtplib.SMTP_SSL(s["host"], port, context=ctx, timeout=timeout)
    else:
        server = smtplib.SMTP(s["host"], port, timeout=timeout)
    try:
        server.ehlo()
        if security == "starttls":
            server.starttls(context=ctx)
            server.ehlo()
        if s.get("username") and s.get("password"):
            server.login(s["username"], s["password"])
        server.send_message(msg)
    finally:
        try:
            server.quit()
        except Exception:
            pass


def send_async(app, message_id, **kwargs):
    """Send in a background thread and record the result on the Message row."""
    def run():
        from models import Message, db
        status = "sent"
        try:
            send_mail(**kwargs)
        except Exception as exc:  # noqa: BLE001
            status = f"failed: {exc}"[:250]
        with app.app_context():
            m = db.session.get(Message, message_id)
            if m:
                m.email_status = status
                db.session.commit()
    threading.Thread(target=run, daemon=True).start()
