#!/usr/bin/env python3
import os
import smtplib
import subprocess
import email.utils
from email.message import EmailMessage
from pathlib import Path

SMTP_HOST = os.environ.get("ELPHEL_SMTP_HOST", "mail.elphel.com")
SMTP_PORT = int(os.environ.get("ELPHEL_SMTP_PORT", "465"))
SMTP_USER = os.environ.get("ELPHEL_SMTP_USER", "codex@elphel.com")
SMTP_PASS = os.environ.get("ELPHEL_SMTP_PASS")
# ELPHEL_SEND_MODE=ssh_sendmail (default) or smtp.
# Defaulting to ssh_sendmail avoids sending from the local LAN IP, which can trigger
# recipient-side policy/reputation blocks.
SEND_MODE = os.environ.get("ELPHEL_SEND_MODE", "ssh_sendmail").lower()
SEND_SSH_HOST = os.environ.get("ELPHEL_SEND_SSH_HOST", "community.elphel.com")
SEND_SSH_USER = os.environ.get("ELPHEL_SEND_SSH_USER", "elphel5")
SEND_SSH_PORT = os.environ.get("ELPHEL_SEND_SSH_PORT", "")
OUT_DIR = os.environ.get("EMAIL_OUT_DIR", "attic/email_outbox")


def _safe_subject(subject):
    return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in subject)[:80] or "message"


def _write_index(index_path, values):
    line = ",".join(v.replace(",", " ") for v in values)
    index_path.parent.mkdir(parents=True, exist_ok=True)
    with index_path.open("a", encoding="utf-8") as f:
        f.write(line + "\n")


def _send_via_smtp(msg, recipients):
    if not SMTP_PASS:
        raise SystemExit("Set ELPHEL_SMTP_PASS")
    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as s:
        s.login(SMTP_USER, SMTP_PASS)
        s.send_message(msg, to_addrs=recipients)


def _send_via_ssh_sendmail(msg):
    ssh_target = f"{SEND_SSH_USER}@{SEND_SSH_HOST}"
    ssh_cmd = ["ssh"]
    if SEND_SSH_PORT:
        ssh_cmd += ["-p", SEND_SSH_PORT]
    ssh_cmd += [ssh_target, "/usr/sbin/sendmail", "-t", "-f", SMTP_USER]
    try:
        subprocess.run(ssh_cmd, input=msg.as_bytes(), check=True)
    except FileNotFoundError:
        raise SystemExit("ssh not found; install openssh-client or use SMTP mode")


def send_email(subject, body, to_addrs, cc_addrs=None):
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = SMTP_USER
    msg["To"] = ", ".join(to_addrs)
    if cc_addrs:
        msg["Cc"] = ", ".join(cc_addrs)
    msg.set_content(body)

    recipients = list(to_addrs) + (list(cc_addrs) if cc_addrs else [])
    out_dir = Path(OUT_DIR)
    date_dir = out_dir / email.utils.formatdate(localtime=True)[:10].replace(" ", "_")
    date_dir.mkdir(parents=True, exist_ok=True)
    safe_subject = _safe_subject(subject)
    seq = f"{len(list(date_dir.glob('*.eml'))) + 1:04d}"
    out_path = date_dir / f"{seq}_{safe_subject}.eml"
    out_path.write_bytes(msg.as_bytes())
    meta_path = date_dir / f"{seq}_meta.txt"
    meta_path.write_text(
        f"From: {SMTP_USER}\nTo: {', '.join(to_addrs)}\nCc: {', '.join(cc_addrs or [])}\nSubject: {subject}\n",
        encoding="utf-8",
    )
    _write_index(out_dir / "index.csv", [email.utils.formatdate(localtime=True), SMTP_USER, ",".join(to_addrs), ",".join(cc_addrs or []), subject, str(out_path)])
    if SEND_MODE == "ssh_sendmail":
        _send_via_ssh_sendmail(msg)
    else:
        _send_via_smtp(msg, recipients)


def main():
    subject = os.environ.get("EMAIL_SUBJECT", "MCP access test")
    body = os.environ.get("EMAIL_BODY", "Hi,\n\nTest message.\n")
    to_addrs = os.environ.get("EMAIL_TO", "").split(",")
    cc_addrs = os.environ.get("EMAIL_CC", "").split(",") if os.environ.get("EMAIL_CC") else []
    to_addrs = [a.strip() for a in to_addrs if a.strip()]
    cc_addrs = [a.strip() for a in cc_addrs if a.strip()]
    if not to_addrs:
        raise SystemExit("Set EMAIL_TO=addr1,addr2")
    send_email(subject, body, to_addrs, cc_addrs)


if __name__ == "__main__":
    main()
