#!/usr/bin/env python3
import email
import imaplib
import os
from email.header import decode_header
from pathlib import Path

IMAP_HOST = os.environ.get("ELPHEL_IMAP_HOST", "mail.elphel.com")
IMAP_PORT = int(os.environ.get("ELPHEL_IMAP_PORT", "993"))
IMAP_USER = os.environ.get("ELPHEL_IMAP_USER", "codex@elphel.com")
IMAP_PASS = os.environ.get("ELPHEL_IMAP_PASS")
MAILBOX = os.environ.get("ELPHEL_IMAP_BOX", "INBOX")
OUT_DIR = Path(os.environ.get("EMAIL_OUT_DIR", "attic/email_inbox"))
SEARCH = os.environ.get("EMAIL_SEARCH", "ALL")


def _decode(value):
    if value is None:
        return ""
    parts = decode_header(value)
    out = ""
    for text, enc in parts:
        if isinstance(text, bytes):
            out += text.decode(enc or "utf-8", errors="replace")
        else:
            out += text
    return out


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 fetch():
    if not IMAP_PASS:
        raise SystemExit("Set ELPHEL_IMAP_PASS")
    with imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT) as imap:
        imap.login(IMAP_USER, IMAP_PASS)
        imap.select(MAILBOX)
        status, data = imap.search(None, SEARCH)
        if status != "OK":
            raise SystemExit("IMAP search failed")
        ids = data[0].split()
        for idx, msg_id in enumerate(ids, start=1):
            status, msg_data = imap.fetch(msg_id, "(RFC822)")
            if status != "OK":
                continue
            raw = msg_data[0][1]
            msg = email.message_from_bytes(raw)
            subject = _decode(msg.get("Subject"))
            date = _decode(msg.get("Date"))
            from_ = _decode(msg.get("From"))
            to_ = _decode(msg.get("To"))
            cc_ = _decode(msg.get("Cc"))
            date_dir = OUT_DIR / (date[:10].replace(" ", "_") if date else "unknown-date")
            date_dir.mkdir(parents=True, exist_ok=True)
            seq = f"{idx:04d}"
            fname = f"{seq}_{_safe_subject(subject)}.eml"
            out_path = date_dir / fname
            out_path.write_bytes(raw)
            meta_path = date_dir / f"{seq}_meta.txt"
            meta_path.write_text(
                f"From: {from_}\nTo: {to_}\nCc: {cc_}\nDate: {date}\nSubject: {subject}\n",
                encoding="utf-8",
            )
            _write_index(OUT_DIR / "index.csv", [date, from_, to_, cc_, subject, str(out_path)])


if __name__ == "__main__":
    fetch()
