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

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

from fliiq.runtime.google_auth import resolve_gmail_creds

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, auth_method, credential = await resolve_gmail_creds()

    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, auth_method, credential, recipients, msg
    )

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


def _send_smtp(
    sender: str, auth_method: str, credential: 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()
            if auth_method == "oauth2":
                auth_string = f"user={sender}\x01auth=Bearer {credential}\x01\x01"
                encoded = base64.b64encode(auth_string.encode()).decode()
                code, resp = server.docmd("AUTH", f"XOAUTH2 {encoded}")
                if code != 235:
                    raise smtplib.SMTPAuthenticationError(code, resp)
            else:
                server.login(sender, credential)
            server.sendmail(sender, recipients, msg.as_string())
    except smtplib.SMTPAuthenticationError:
        if auth_method == "oauth2":
            raise ValueError(
                f"Gmail SMTP OAuth failed for {sender}. "
                "Try 'fliiq google auth' to re-authorize."
            )
        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}")
