"""Send email via Gmail SMTP with app password authentication."""

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

SMTP_HOST = "smtp.gmail.com"
SMTP_PORT = 587


async def handler(params: dict) -> dict:
    """Send an email via Gmail SMTP."""
    to_raw = params["to"]
    subject = params["subject"]
    body = params["body"]

    sender = params.get("gmail_address") or os.environ.get("GMAIL_ADDRESS")
    if not sender:
        raise ValueError("Provide gmail_address param or set GMAIL_ADDRESS env var.")

    app_password = params.get("gmail_app_password") or os.environ.get("GMAIL_APP_PASSWORD")
    if not app_password:
        raise ValueError(
            "Provide gmail_app_password param or set GMAIL_APP_PASSWORD env var. "
            "Generate one at https://myaccount.google.com/apppasswords"
        )

    recipients = [addr.strip() for addr in to_raw.split(",") if addr.strip()]
    if not recipients:
        raise ValueError("No valid recipient email addresses provided.")

    msg = MIMEText(body, "plain")
    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = ", ".join(recipients)

    loop = asyncio.get_running_loop()
    await loop.run_in_executor(None, _send_smtp, sender, app_password, recipients, msg)

    return {"status": f"Email sent to {', '.join(recipients)}"}


def _send_smtp(
    sender: str, app_password: str, recipients: list[str], msg: MIMEText
) -> None:
    """Blocking SMTP send — runs in threadpool."""
    try:
        with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
            server.starttls()
            server.login(sender, app_password)
            server.sendmail(sender, recipients, msg.as_string())
    except smtplib.SMTPAuthenticationError:
        raise ValueError(
            "Gmail authentication failed. Check GMAIL_ADDRESS and GMAIL_APP_PASSWORD. "
            "Ensure 2FA is enabled and you're using an app password, not your account password."
        )
    except smtplib.SMTPException as e:
        raise ValueError(f"SMTP error: {e}")
