"""SMTP email delivery for contact + sponsorship inquiries.

Provider-agnostic: point the SMTP_* settings at Gmail, SendGrid, AWS SES,
Mailgun, etc. Sends are fire-and-forget via FastAPI BackgroundTasks, so a slow
or failing mail server never blocks (or fails) the API response — the submission
is already persisted in MySQL by the time we get here.
"""

from __future__ import annotations

import logging
import smtplib
from email.message import EmailMessage
from email.utils import formataddr

from .config import get_settings

logger = logging.getLogger("cycleyatra.email")


def _send(
    *,
    to: list[str],
    subject: str,
    body: str,
    reply_to: str | None = None,
) -> None:
    """Build and send a single plaintext email. Never raises — logs instead."""
    settings = get_settings()

    if not settings.mail_enabled:
        logger.info("MAIL disabled; would send %r to %s", subject, to)
        return
    if not to:
        logger.warning("No recipients for %r; skipping send", subject)
        return

    msg = EmailMessage()
    msg["From"] = formataddr((settings.mail_from_name, settings.mail_from))
    msg["To"] = ", ".join(to)
    msg["Subject"] = subject
    if reply_to:
        msg["Reply-To"] = reply_to
    msg.set_content(body)

    try:
        if settings.smtp_use_ssl:
            server: smtplib.SMTP = smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, timeout=15)
        else:
            server = smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=15)
        with server:
            if settings.smtp_use_tls and not settings.smtp_use_ssl:
                server.starttls()
            if settings.smtp_user:
                server.login(settings.smtp_user, settings.smtp_password)
            server.send_message(msg)
        logger.info("Sent %r to %s", subject, to)
    except Exception:  # noqa: BLE001 - background task must not propagate
        logger.exception("Failed to send %r to %s", subject, to)


# --- Composed sends -------------------------------------------------------

def send_contact_emails(
    *, name: str, email: str, phone: str, message: str | None
) -> None:
    """Notify organizers of a contact submission, then auto-reply to the sender."""
    settings = get_settings()

    _send(
        to=settings.contact_recipients_list,
        subject=f"[Contact] {name}",
        reply_to=email,
        body=(
            "New contact form submission:\n\n"
            f"Name:    {name}\n"
            f"Email:   {email}\n"
            f"Phone:   {phone}\n"
            f"Message: {message or '(none)'}\n"
        ),
    )

    _send(
        to=[email],
        subject="We received your message — CycleYatra 2026",
        body=(
            f"Namaste {name},\n\n"
            "Thank you for reaching out to the Rameswaram to Ayodhya Cycling "
            "Yatra 2026 team. We have received your message and will get back "
            "to you shortly.\n\n"
            "Jai Shree Ram,\n"
            "Team CycleYatra"
        ),
    )


def send_sponsorship_emails(
    *,
    company: str,
    contact_name: str,
    tier: str,
    email: str | None,
    phone: str | None,
    message: str | None,
) -> None:
    """Notify organizers of a sponsorship request, then auto-reply with the deck."""
    settings = get_settings()

    _send(
        to=settings.sponsorship_recipients_list,
        subject=f"[Sponsorship] {company} — {tier}",
        reply_to=email or None,
        body=(
            "New sponsorship request:\n\n"
            f"Company: {company}\n"
            f"Contact: {contact_name}\n"
            f"Tier:    {tier}\n"
            f"Email:   {email or '(not provided)'}\n"
            f"Phone:   {phone or '(not provided)'}\n"
            f"Message: {message or '(none)'}\n"
        ),
    )

    if email:
        deck_line = (
            f"You can access our official Sponsorship Deck here:\n{settings.sponsor_deck_url}\n\n"
            if settings.sponsor_deck_url
            else "Our official Sponsorship Deck will follow in a separate email.\n\n"
        )
        _send(
            to=[email],
            subject="Your Sponsorship Deck — CycleYatra 2026",
            body=(
                f"Namaste {contact_name},\n\n"
                f"Thank you for {company}'s interest in partnering with the "
                "Rameswaram to Ayodhya Cycling Yatra 2026 "
                f"({tier}).\n\n"
                f"{deck_line}"
                "Our partnerships team will reach out to discuss the next steps.\n\n"
                "Jai Shree Ram,\n"
                "Team CycleYatra"
            ),
        )
