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


def _send_sync(to: str, subject: str, body: str) -> None:
    host = os.environ.get("SMTP_HOST", "")
    port = int(os.environ.get("SMTP_PORT", 587))
    user = os.environ.get("SMTP_USER", "")
    password = os.environ.get("SMTP_PASSWORD", "")
    from_ = os.environ.get("SMTP_FROM") or user

    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:
    await asyncio.to_thread(_send_sync, to, subject, body)
