from __future__ import annotations

import smtplib
from email.message import EmailMessage

from . import settings


class MailerError(RuntimeError):
    """Signal a mail delivery problem without leaking provider internals."""

    pass


def send_text_email(*, to_addr: str, subject: str, body: str) -> None:
    """Send a plaintext email through the configured SMTP relay."""

    if not to_addr:
        raise MailerError("missing recipient")
    if not settings.SMTP_HOST:
        raise MailerError("smtp not configured")

    message = EmailMessage()
    message["From"] = settings.SMTP_FROM
    message["To"] = to_addr
    message["Subject"] = subject
    message.set_content(body)

    smtp_cls = smtplib.SMTP_SSL if settings.SMTP_USE_TLS else smtplib.SMTP
    try:
        with smtp_cls(settings.SMTP_HOST, settings.SMTP_PORT, timeout=settings.SMTP_TIMEOUT_SEC) as client:
            if settings.SMTP_STARTTLS and not settings.SMTP_USE_TLS:
                client.starttls()
            if settings.SMTP_USERNAME:
                client.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)
            client.send_message(message)
    except Exception as exc:
        raise MailerError("failed to send email") from exc


def access_request_verification_body(*, request_code: str, verify_url: str) -> str:
    """Render the access-request email verification message body."""

    return "\n".join(
        [
            "Atlas — confirm your email",
            "",
            "Someone requested an Atlas account using this email address.",
            "",
            f"Request code: {request_code}",
            "",
            "To confirm this request, open:",
            verify_url,
            "",
            "If you did not request access, you can ignore this email.",
            "",
        ]
    )
