"""Mail transport abstraction — pluggable so dev and prod can use the
same code path with different backends.

In dev: console-log mode (default). Calls to `send_mail` print the
message to stdout / the Flask log. No SMTP, no API keys, no external
dependencies. Click-through testing works just by copying the magic
link out of the terminal.

On staging.arpartsfinder.com (pair, mod_passenger): use `file`
transport. Python's stdout under mod_passenger lands in pair's
Apache error log which is hard to tail. Writing to a known file in
the app's tmp/ dir lets us `ssh ... 'cat tmp/mail.log'` to grab
magic links during cutover testing.

In prod: pluggable via the `MAIL_TRANSPORT` config key. Backends we
might add: `sendmail` (pair.com's host MTA), `smtp` (any SMTP server),
`postmark` / `sendgrid` / `mailgun` (transactional providers). All
implement the same `(to, subject, body) -> None` contract.

Adding a new backend = adding a new branch in `send_mail()` plus its
config keys. Configuration lives in `settings.load_config()` (already
the source of truth for site-ng config).
"""

from __future__ import annotations

import datetime
import logging
import smtplib
import subprocess
from email.mime.text import MIMEText
from pathlib import Path

from flask import current_app

logger = logging.getLogger(__name__)


def send_mail(to: str, subject: str, body: str) -> None:
    """Send an email via whatever transport this environment is wired
    for. Caller's responsibility to format `body` (plain text v1; we
    can add HTML later by extending the contract).

    The transport is selected by `MAIL_TRANSPORT` in app config:
      - "console" (default) — print to stdout. Dev mode.
      - "file"              — append to MAIL_FILE_PATH (good for
                              staging where stdout isn't tail-able).
      - "sendmail"          — pipe to /usr/sbin/sendmail.
      - "smtp"              — connect to MAIL_SMTP_HOST:MAIL_SMTP_PORT.
      - (future) "postmark" / "sendgrid" / etc.

    Never raises — a mail failure is logged but doesn't bubble up, so
    a downstream mail outage can't take down a request. The caller
    should already have committed any DB state before calling here.
    """
    transport = current_app.config.get("MAIL_TRANSPORT", "console")
    try:
        if transport == "console":
            _send_console(to, subject, body)
        elif transport == "file":
            _send_file(to, subject, body)
        elif transport == "sendmail":
            _send_sendmail(to, subject, body)
        elif transport == "smtp":
            _send_smtp(to, subject, body)
        else:
            logger.warning("unknown MAIL_TRANSPORT=%r — falling back to console",
                           transport)
            _send_console(to, subject, body)
    except Exception:
        logger.exception("send_mail failed (to=%s subject=%r)", to, subject)


def _from_addr() -> str:
    return current_app.config.get("MAIL_FROM",
                                   "noreply@arpartsfinder.com")


def _send_console(to: str, subject: str, body: str) -> None:
    """Dev backend: print the message to stdout so the developer can
    copy the magic link straight out of the terminal."""
    border = "─" * 72
    print(f"\n{border}\n📧  dev-mode email (MAIL_TRANSPORT=console)\n"
          f"From:    {_from_addr()}\nTo:      {to}\n"
          f"Subject: {subject}\n{border}\n{body}\n{border}\n",
          flush=True)


def _send_file(to: str, subject: str, body: str) -> None:
    """Staging backend: append the message to a logfile so we can
    `ssh ... 'cat tmp/mail.log'` to grab the magic link. Path is
    resolved relative to the app root (the directory containing
    passenger_wsgi.py, which is the parent of ngsite/) so a
    config value of "tmp/mail.log" lands at
    `<app_root>/tmp/mail.log` — outside the web docroot and not
    served by Apache. Default `tmp/mail.log`."""
    raw = current_app.config.get("MAIL_FILE_PATH") or "tmp/mail.log"
    p = Path(raw)
    if not p.is_absolute():
        # current_app.root_path is the package dir (ngsite/); its
        # parent is the app root. Same convention as the deploy
        # script's REMOTE_ROOT.
        p = Path(current_app.root_path).parent / p
    p.parent.mkdir(parents=True, exist_ok=True)
    border = "─" * 72
    ts = datetime.datetime.now().isoformat(timespec="seconds")
    with p.open("a", encoding="utf-8") as f:
        f.write(f"{border}\n{ts}  MAIL_TRANSPORT=file\n"
                f"From:    {_from_addr()}\nTo:      {to}\n"
                f"Subject: {subject}\n{border}\n{body}\n{border}\n\n")


def _send_sendmail(to: str, subject: str, body: str) -> None:
    """Prod backend (option A): pipe to the host's sendmail. Works on
    pair.com out of the box; deliverability depends on pair's IP rep.
    Uses subprocess with input so the message body never lands in the
    process arglist."""
    msg = MIMEText(body, _charset="utf-8")
    msg["From"] = _from_addr()
    msg["To"] = to
    msg["Subject"] = subject
    sendmail_path = current_app.config.get("MAIL_SENDMAIL_PATH",
                                            "/usr/sbin/sendmail")
    subprocess.run(
        [sendmail_path, "-t", "-oi"],
        input=msg.as_string(), text=True, check=True,
        timeout=10)


def _send_smtp(to: str, subject: str, body: str) -> None:
    """Prod backend (option B): SMTP server. Configure host/port/user/
    password via MAIL_SMTP_* keys. STARTTLS used when MAIL_SMTP_TLS=1."""
    cfg = current_app.config
    msg = MIMEText(body, _charset="utf-8")
    msg["From"] = _from_addr()
    msg["To"] = to
    msg["Subject"] = subject

    host = cfg.get("MAIL_SMTP_HOST", "localhost")
    port = int(cfg.get("MAIL_SMTP_PORT", 25))
    user = cfg.get("MAIL_SMTP_USER")
    pw = cfg.get("MAIL_SMTP_PASSWORD")
    use_tls = bool(int(cfg.get("MAIL_SMTP_TLS", 0)))

    with smtplib.SMTP(host, port, timeout=10) as s:
        if use_tls:
            s.starttls()
        if user:
            s.login(user, pw or "")
        s.sendmail(_from_addr(), [to], msg.as_string())
