import logging
import smtplib
from email.message import EmailMessage
from typing import Any

from app.core.config import settings
from app.services.email_templates import render_email

logger = logging.getLogger("yeneb.email")


def send_email(to: str, subject: str, message: str, html: str | None = None) -> None:
    """Send an email via our own domain's SMTP mailbox (port 465,
    implicit SSL/TLS — see smtp_port in app.core.config).

    Every email send in this codebase goes through this one function.
    Only makes a real SMTP connection when smtp_password is
    configured — otherwise (local dev, tests) this just logs, so the
    test suite (which triggers an OTP email whenever a customer picks
    the "email" channel) never touches the network.

    html is optional — when given, the message becomes a real
    multipart/alternative email (plain text first, HTML second, per
    RFC 2046's "most preferred last" convention — EmailMessage.
    add_alternative already builds this correctly) instead of a plain
    text-only one. message is never optional even then: it's the
    fallback every client without HTML rendering (and every screen
    reader) actually uses, not just a formality. See
    app.services.email_templates for how the two are generated
    together from one Jinja2 template pair.

    The full message (which usually contains the OTP code itself) is
    only ever logged in development, same reasoning as
    app.services.sms.send_sms — outside development, only the fact
    that a send happened is logged, never the body.
    """
    if settings.environment == "development":
        logger.info("Email to %s: %s — %s", to, subject, message)
    else:
        logger.info("Email to %s: %s", to, subject)
    if not settings.smtp_password:
        return

    email = EmailMessage()
    email["Subject"] = subject
    email["From"] = f"{settings.smtp_sender_name} <{settings.smtp_username}>"
    email["To"] = to
    email.set_content(message)
    if html is not None:
        email.add_alternative(html, subtype="html")

    with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port) as smtp:
        smtp.login(settings.smtp_username, settings.smtp_password)
        smtp.send_message(email)


def send_templated_email(
    to: str, subject: str, template_name: str, context: dict[str, Any]
) -> None:
    """Renders {template_name}.html/.txt from app/templates/email/
    (see app.services.email_templates.render_email) and sends both
    parts through send_email. subject is injected into the render
    context automatically (base.html's <title> uses it) — callers
    only pass it once, not both as the email header and separately in
    context."""
    html, text = render_email(template_name, {"subject": subject, **context})
    send_email(to, subject, text, html=html)
