import os
import asyncio
import smtplib
from email.mime.text import MIMEText


def _send_sync(
    to: str,
    subject: str,
    body: str,
    host: str,
    port: int,
    user: str,
    password: str,
    from_: str,
) -> None:
    if not host:
        raise RuntimeError("SMTP_HOST is not configured")

    msg = MIMEText(body, "plain")
    msg["Subject"] = subject
    msg["From"] = from_
    msg["To"] = to

    with smtplib.SMTP(host, port) as smtp:
        smtp.starttls()
        if user:
            smtp.login(user, password)
        smtp.send_message(msg)


async def send_email(to: str, subject: str, body: str) -> None:
    import db as db_module

    host = await db_module.get_setting("host", "smtp") or os.environ.get(
        "SMTP_HOST", ""
    )
    port = int(
        await db_module.get_setting("port", "smtp") or os.environ.get("SMTP_PORT", 587)
    )
    user = await db_module.get_setting("user", "smtp") or os.environ.get(
        "SMTP_USER", ""
    )
    password = await db_module.get_setting("password", "smtp") or os.environ.get(
        "SMTP_PASSWORD", ""
    )
    from_ = (
        await db_module.get_setting("from", "smtp")
        or os.environ.get("SMTP_FROM", "")
        or user
    )
    await asyncio.to_thread(
        _send_sync, to, subject, body, host, port, user, password, from_
    )
