#!/usr/bin/env python3
import os
import smtplib
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")
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_email(subject, body, to_addrs, cc_addrs=None):
    if not SMTP_PASS:
        raise SystemExit("Set ELPHEL_SMTP_PASS")
    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)])
    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as s:
        s.login(SMTP_USER, SMTP_PASS)
        s.send_message(msg, to_addrs=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()
