#!/usr/bin/env python3
"""pmail - read ProtonMail via the local Proton Mail Bridge IMAP server.

Zero dependencies (Python 3 stdlib only). Strictly read-only: bodies are
fetched with BODY.PEEK, mailboxes are opened with EXAMINE, and no command
ever stores flags, moves, or deletes mail.

Cache: ~/.local/share/pmail/mail.db (SQLite + FTS5, rebuildable).
Credentials: macOS Keychain (service "pmail-bridge") or the PMAIL_PASSWORD
env var; account email from PMAIL_ACCOUNT or `pmail setup`. Override the
server with PMAIL_HOST / PMAIL_PORT.

All data commands print JSON on stdout; progress and errors go to stderr.
"""

import argparse
import getpass
import imaplib
import json
import os
import re
import sqlite3
import ssl
import subprocess
import sys
import time
from datetime import datetime, timezone
from email import policy
from email.parser import BytesParser
from email.utils import parsedate_to_datetime

IMAP_HOST = os.environ.get("PMAIL_HOST", "127.0.0.1")
IMAP_PORT = int(os.environ.get("PMAIL_PORT", "1143"))
KEYCHAIN_SERVICE = "pmail-bridge"
DATA_DIR = os.path.expanduser(os.environ.get("PMAIL_DATA", "~/.local/share/pmail"))
DB_PATH = os.path.join(DATA_DIR, "mail.db")
ATTACH_DIR = os.path.join(DATA_DIR, "attachments")
CONFIG_PATH = os.path.join(DATA_DIR, "config.json")

def account():
    """Proton account email: $PMAIL_ACCOUNT, else the config written by setup."""
    a = os.environ.get("PMAIL_ACCOUNT")
    if a:
        return a
    try:
        with open(CONFIG_PATH) as f:
            a = json.load(f).get("account")
            if a:
                return a
    except (OSError, json.JSONDecodeError):
        pass
    die("no account configured - run `pmail setup` first (or set PMAIL_ACCOUNT)")

DEFAULT_LIMIT = 20
SYNC_STALENESS = 60      # seconds; implicit sync runs at most this often
QUICK_SEED = 500         # newest N UIDs synced on every incremental sync
BACKFILL_BATCH = 200     # UID window per backfill step (cursor persisted per step)
FETCH_CHUNK = 100        # messages per IMAP FETCH command

# ---------------------------------------------------------------- utilities

def die(msg, code=1):
    print(f"pmail: error: {msg}", file=sys.stderr)
    sys.exit(code)

def log(msg):
    print(msg, file=sys.stderr)

def emit(obj):
    print(json.dumps(obj, indent=2, ensure_ascii=False))

def quote_mailbox(name):
    return '"' + name.replace("\\", "\\\\").replace('"', '\\"') + '"'

def iso(ts):
    if ts is None:
        return None
    return datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

# ------------------------------------------------------------- credentials

def get_password():
    pw = os.environ.get("PMAIL_PASSWORD")
    if pw:
        return pw
    r = subprocess.run(
        ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account(), "-w"],
        capture_output=True, text=True)
    if r.returncode != 0:
        die(f"no credentials: store the Bridge password with `pmail setup`, "
            f"or set PMAIL_PASSWORD (Keychain service '{KEYCHAIN_SERVICE}', account '{account()}')")
    return r.stdout.rstrip("\n")

# ------------------------------------------------------------------- IMAP

def connect():
    """Connect + login. Dies with an actionable message if Bridge is down."""
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    try:
        m = imaplib.IMAP4(IMAP_HOST, IMAP_PORT, timeout=30)
        m.starttls(ctx)
    except (OSError, ssl.SSLError) as e:
        die(f"cannot reach Proton Mail Bridge at {IMAP_HOST}:{IMAP_PORT} - "
            f"is the Proton Mail Bridge app running? ({e})")
    try:
        m.login(account(), get_password())
    except imaplib.IMAP4.error as e:
        die(f"Bridge login failed for {account()}: {e}. "
            f"Get the current password from Bridge > Mailbox details and run `pmail setup`.")
    return m

def try_connect():
    """Like connect(), but returns None instead of dying (for implicit sync)."""
    try:
        return connect()
    except SystemExit:
        return None

UID_RE = re.compile(rb"UID (\d+)")
FLAGS_RE = re.compile(rb"FLAGS \(([^)]*)\)")

def parse_fetch_meta(header):
    uid_m = UID_RE.search(header)
    flags_m = FLAGS_RE.search(header)
    return (int(uid_m.group(1)) if uid_m else None,
            flags_m.group(1).decode(errors="replace") if flags_m else "")

def iter_fetch(data):
    """Yield (uid, flags, literal_bytes) from an imaplib FETCH response.
    Gluon appends 'UID n' AFTER the literal, so combine each tuple's header
    with the trailing bytes item that follows it."""
    for i, item in enumerate(data):
        if isinstance(item, tuple):
            blob = item[0]
            if i + 1 < len(data) and isinstance(data[i + 1], bytes):
                blob += data[i + 1]
            uid, flags = parse_fetch_meta(blob)
            if uid is not None and isinstance(item[1], bytes):
                yield uid, flags, item[1]

def fetch_full(m, uids):
    """UID FETCH (FLAGS BODY.PEEK[]) for the given UIDs, in chunks.
    Yields (uid, flags, raw_bytes)."""
    for i in range(0, len(uids), FETCH_CHUNK):
        chunk = uids[i:i + FETCH_CHUNK]
        typ, data = m.uid("FETCH", ",".join(map(str, chunk)), "(FLAGS BODY.PEEK[])")
        if typ != "OK":
            log(f"warning: FETCH failed for chunk starting at UID {chunk[0]}, skipping")
            continue
        yield from iter_fetch(data)

def fetch_headers(m, uids):
    """UID FETCH (FLAGS BODY.PEEK[HEADER.FIELDS ...]) -> list of summary dicts."""
    out = []
    fields = "(FLAGS BODY.PEEK[HEADER.FIELDS (FROM TO CC BCC SUBJECT DATE)])"
    for i in range(0, len(uids), FETCH_CHUNK):
        chunk = uids[i:i + FETCH_CHUNK]
        typ, data = m.uid("FETCH", ",".join(map(str, chunk)), fields)
        if typ != "OK":
            continue
        for uid, flags, hdr_bytes in iter_fetch(data):
            msg = BytesParser(policy=policy.default).parsebytes(hdr_bytes)
            out.append({
                "uid": uid,
                "date": iso(parse_date(safe_header(msg, "Date"))),
                "from": safe_header(msg, "From"),
                "to": safe_header(msg, "To"),
                "bcc": safe_header(msg, "Bcc"),
                "subject": safe_header(msg, "Subject"),
                "flags": flags,
            })
    return out

def fetch_bcc(m, uids):
    """UID FETCH BODY.PEEK[HEADER.FIELDS (BCC)] -> {uid: bcc}, in chunks.
    Every UID in a successful FETCH gets an entry ('' when the message has no
    Bcc or no longer exists), so callers can mark those rows as fetched."""
    out = {}
    for i in range(0, len(uids), FETCH_CHUNK):
        chunk = uids[i:i + FETCH_CHUNK]
        typ, data = m.uid("FETCH", ",".join(map(str, chunk)),
                          "(BODY.PEEK[HEADER.FIELDS (BCC)])")
        if typ != "OK":
            log(f"warning: Bcc FETCH failed for chunk starting at UID {chunk[0]}, skipping")
            continue
        out.update(dict.fromkeys(chunk, ""))
        for uid, _flags, hdr_bytes in iter_fetch(data):
            msg = BytesParser(policy=policy.default).parsebytes(hdr_bytes)
            out[uid] = safe_header(msg, "Bcc")
    return out

# ----------------------------------------------------------------- parsing

def safe_str(header):
    if header is None:
        return ""
    try:
        return str(header)
    except Exception:
        return str(header.raw) if hasattr(header, "raw") else ""

FOLD_RE = re.compile(r"\r?\n[ \t]+")

def safe_header(msg, name):
    """Header value as a string. The structured parser in policy.default can
    raise on malformed headers (in msg.get itself, not just str()); fall back
    to the raw, unfolded value so one bad header doesn't lose the message."""
    try:
        return safe_str(msg.get(name))
    except Exception:
        for k, v in msg.raw_items():
            if k.lower() == name.lower():
                return FOLD_RE.sub(" ", str(v)).strip()
        return ""

def parse_date(header):
    if not header:
        return None
    try:
        dt = parsedate_to_datetime(str(header))
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        return int(dt.timestamp())
    except Exception:
        return None

def part_text(part):
    try:
        content = part.get_content()
        if isinstance(content, bytes):
            return content.decode("utf-8", errors="replace")
        return content or ""
    except Exception:
        try:
            payload = part.get_payload(decode=True)
            return payload.decode("utf-8", errors="replace") if payload else ""
        except Exception:
            return ""

def parse_message(raw):
    """Parse a raw RFC822 message into a cache record."""
    msg = BytesParser(policy=policy.default).parsebytes(raw)
    text_parts, html_parts, attachments = [], [], []
    for part in msg.walk():
        if part.get_content_maintype() == "multipart":
            continue
        ctype = part.get_content_type()
        filename = part.get_filename()
        if part.get_content_disposition() == "attachment" or filename:
            try:
                payload = part.get_payload(decode=True)
            except Exception:
                payload = None
            attachments.append({
                "index": len(attachments) + 1,
                "name": filename or "unnamed",
                "mime": ctype,
                "size": len(payload) if payload else 0,
            })
        elif ctype == "text/plain":
            text_parts.append(part_text(part))
        elif ctype == "text/html":
            html_parts.append(part_text(part))
    body_text = "\n".join(p for p in text_parts if p).strip()
    body_html = "\n".join(p for p in html_parts if p).strip()
    if not body_text and body_html:
        # ~97% of real mail is HTML-only; index the stripped text so FTS works
        body_text = html_to_text(body_html)
    else:
        body_text = INVISIBLES_RE.sub("", body_text)
    return {
        "message_id": safe_header(msg, "Message-ID"),
        "date": parse_date(safe_header(msg, "Date")),
        "from_addr": safe_header(msg, "From"),
        "to_addr": safe_header(msg, "To"),
        "cc": safe_header(msg, "Cc"),
        "bcc": safe_header(msg, "Bcc"),
        "subject": safe_header(msg, "Subject"),
        "size": len(raw),
        "body_text": body_text,
        "body_html": body_html,
        "attachments": json.dumps(attachments, ensure_ascii=False),
    }

HTML_TAG_RE = re.compile(r"<[^>]+>")
HTML_STRIP_RE = re.compile(r"(?is)<(script|style|head)[^>]*>.*?</\1>|<!--.*?-->")
INVISIBLES_RE = re.compile(
    "[\u00ad\u034f\u200b-\u200f\u202a-\u202e\u2060\ufeff]")  # zero-width/format junk

def html_to_text(html):
    txt = HTML_STRIP_RE.sub(" ", html)   # drop style/script/head bodies + comments
    txt = HTML_TAG_RE.sub(" ", txt)
    txt = INVISIBLES_RE.sub("", txt)
    txt = re.sub(r"[ \t]+", " ", txt)
    txt = re.sub(r"\n\s*\n\s*\n+", "\n\n", txt)
    for ent, ch in (("&amp;", "&"), ("&lt;", "<"), ("&gt;", ">"),
                    ("&quot;", '"'), ("&#39;", "'"), ("&nbsp;", " ")):
        txt = txt.replace(ent, ch)
    return txt.strip()

# ------------------------------------------------------------------- cache

# bcc: NULL = not fetched yet (row cached before Bcc support), '' = none.
# The FTS update trigger only re-indexes when an indexed column changes, so
# flag reconciles and the Bcc backfill don't re-tokenize every body.
SCHEMA = """
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS messages (
  mailbox TEXT NOT NULL,
  uid INTEGER NOT NULL,
  message_id TEXT,
  date INTEGER,
  from_addr TEXT,
  to_addr TEXT,
  cc TEXT,
  bcc TEXT,
  subject TEXT,
  flags TEXT DEFAULT '',
  size INTEGER,
  body_text TEXT,
  body_html TEXT,
  attachments TEXT DEFAULT '[]',
  synced_at INTEGER,
  PRIMARY KEY (mailbox, uid)
);
CREATE VIRTUAL TABLE IF NOT EXISTS mail_fts USING fts5(
  subject, from_addr, to_addr, body_text, bcc,
  content='messages', content_rowid='rowid'
);
CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
  INSERT INTO mail_fts(rowid, subject, from_addr, to_addr, body_text, bcc)
  VALUES (new.rowid, new.subject, new.from_addr, new.to_addr, new.body_text, new.bcc);
END;
CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
  INSERT INTO mail_fts(mail_fts, rowid, subject, from_addr, to_addr, body_text, bcc)
  VALUES ('delete', old.rowid, old.subject, old.from_addr, old.to_addr, old.body_text, old.bcc);
END;
CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages
WHEN old.subject IS NOT new.subject OR old.from_addr IS NOT new.from_addr
  OR old.to_addr IS NOT new.to_addr OR old.body_text IS NOT new.body_text
  OR old.bcc IS NOT new.bcc
BEGIN
  INSERT INTO mail_fts(mail_fts, rowid, subject, from_addr, to_addr, body_text, bcc)
  VALUES ('delete', old.rowid, old.subject, old.from_addr, old.to_addr, old.body_text, old.bcc);
  INSERT INTO mail_fts(rowid, subject, from_addr, to_addr, body_text, bcc)
  VALUES (new.rowid, new.subject, new.from_addr, new.to_addr, new.body_text, new.bcc);
END;
CREATE TABLE IF NOT EXISTS sync_state (
  mailbox TEXT PRIMARY KEY,
  uidvalidity INTEGER,
  backfill_cursor INTEGER DEFAULT 0,
  uidnext INTEGER,
  synced_at INTEGER
);
"""

UPSERT = """
INSERT INTO messages
  (mailbox, uid, message_id, date, from_addr, to_addr, cc, bcc, subject,
   flags, size, body_text, body_html, attachments, synced_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(mailbox, uid) DO UPDATE SET
  message_id=excluded.message_id, date=excluded.date,
  from_addr=excluded.from_addr, to_addr=excluded.to_addr, cc=excluded.cc,
  bcc=excluded.bcc,
  subject=excluded.subject, flags=excluded.flags, size=excluded.size,
  body_text=excluded.body_text, body_html=excluded.body_html,
  attachments=excluded.attachments, synced_at=excluded.synced_at
"""

def columns(db, table):
    return {r[1] for r in db.execute(f"PRAGMA table_info({table})")}

def migrate(db):
    """Upgrade a pre-Bcc cache in place (no re-sync). Existing rows get
    bcc=NULL and are filled by the Bcc backfill on the next `pmail sync`."""
    if "bcc" not in columns(db, "messages"):
        db.execute("ALTER TABLE messages ADD COLUMN bcc TEXT")
    if "bcc" not in columns(db, "mail_fts"):
        # FTS5 columns can't be altered: recreate the index and its triggers
        log("pmail: upgrading search index for Bcc (one-off, may take a minute)")
        db.executescript("""
          DROP TRIGGER IF EXISTS messages_ai;
          DROP TRIGGER IF EXISTS messages_ad;
          DROP TRIGGER IF EXISTS messages_au;
          DROP TABLE IF EXISTS mail_fts;""")
        db.executescript(SCHEMA)
        db.execute("INSERT INTO mail_fts(mail_fts) VALUES ('rebuild')")
        db.commit()

def open_db():
    os.makedirs(DATA_DIR, exist_ok=True)
    db = sqlite3.connect(DB_PATH)
    db.executescript(SCHEMA)
    migrate(db)
    return db

def insert_record(db, box, rec, uid, flags):
    db.execute(UPSERT, (
        box, uid, rec["message_id"], rec["date"], rec["from_addr"], rec["to_addr"],
        rec["cc"], rec["bcc"], rec["subject"], flags, rec["size"], rec["body_text"],
        rec["body_html"], rec["attachments"], int(time.time())))

def cached_count(db, box):
    return db.execute("SELECT COUNT(*) FROM messages WHERE mailbox=?", (box,)).fetchone()[0]

def get_sync_row(db, box):
    return db.execute(
        "SELECT uidvalidity, backfill_cursor, uidnext, synced_at FROM sync_state WHERE mailbox=?",
        (box,)).fetchone()

# -------------------------------------------------------------------- sync

def mailbox_status(m, box):
    typ, st = m.status(quote_mailbox(box), "(UIDVALIDITY UIDNEXT MESSAGES)")
    if typ != "OK" or not st or not st[0]:
        die(f"STATUS failed for mailbox '{box}'")
    vals = dict(re.findall(r"(\w+) (\d+)", st[0].decode(errors="replace")))
    return {"uidvalidity": int(vals.get("UIDVALIDITY", 0)),
            "uidnext": int(vals.get("UIDNEXT", 1)),
            "messages": int(vals.get("MESSAGES", 0))}

def fetch_missing(db, m, box, uids):
    """Fetch and cache any of `uids` not already in the db. Returns counts."""
    if not uids:
        return 0, 0
    placeholders = ",".join("?" * len(uids))
    have = {r[0] for r in db.execute(
        f"SELECT uid FROM messages WHERE mailbox=? AND uid IN ({placeholders})",
        (box, *uids))}
    missing = [u for u in uids if u not in have]
    fetched = 0
    for uid, flags, raw in fetch_full(m, missing):
        insert_record(db, box, parse_message(raw), uid, flags)
        fetched += 1
    db.commit()
    return fetched, len(uids) - len(missing)

def reconcile_flags(db, m, box):
    """Pull FLAGS for every UID in the mailbox; update only rows that changed."""
    typ, data = m.uid("FETCH", "1:*", "(FLAGS)")
    if typ != "OK":
        return 0
    changed = 0
    for item in data:
        blob = item[0] if isinstance(item, tuple) else item
        if not isinstance(blob, bytes):
            continue
        uid_m, flags_m = UID_RE.search(blob), FLAGS_RE.search(blob)
        if uid_m and flags_m:
            flags = flags_m.group(1).decode(errors="replace")
            cur = db.execute(
                "UPDATE messages SET flags=? WHERE mailbox=? AND uid=? AND flags != ?",
                (flags, box, int(uid_m.group(1)), flags))
            changed += cur.rowcount
    db.commit()
    return changed

def backfill_bcc(db, m, box, progress=True):
    """Fill bcc for rows cached before Bcc support (bcc IS NULL) by fetching
    only the Bcc header. Resumable: each committed chunk is marked done."""
    uids = [r[0] for r in db.execute(
        "SELECT uid FROM messages WHERE mailbox=? AND bcc IS NULL ORDER BY uid", (box,))]
    if not uids:
        return 0
    if progress:
        log(f"{box}: fetching Bcc for {len(uids)} previously cached message(s)")
    found = 0
    step = FETCH_CHUNK * 10
    for i in range(0, len(uids), step):
        got = fetch_bcc(m, uids[i:i + step])
        db.executemany("UPDATE messages SET bcc=? WHERE mailbox=? AND uid=?",
                       [(v, box, u) for u, v in got.items()])
        db.commit()
        found += sum(1 for v in got.values() if v)
    if progress and found:
        log(f"{box}: found Bcc recipients on {found} message(s)")
    return found

def sync_mailbox(db, m, box, full=False, batch=BACKFILL_BATCH, quick=QUICK_SEED,
                 progress=True):
    m.select(quote_mailbox(box), readonly=True)
    st = mailbox_status(m, box)
    row = get_sync_row(db, box)
    if row is None:
        cursor = 0
        db.execute("INSERT INTO sync_state (mailbox, uidvalidity, backfill_cursor) VALUES (?,?,0)",
                   (box, st["uidvalidity"]))
        db.commit()
    elif row[0] != st["uidvalidity"]:
        if progress:
            log(f"{box}: UIDVALIDITY changed ({row[0]} -> {st['uidvalidity']}); "
                f"wiping {cached_count(db, box)} cached rows")
        db.execute("DELETE FROM messages WHERE mailbox=?", (box,))
        cursor = 0
    else:
        cursor = row[1]

    typ, d = m.uid("SEARCH", "ALL")
    server_uids = sorted(int(u) for u in d[0].split()) if d and d[0] else []
    fetched = skipped = 0

    # 1. recent-first seed: newest `quick` UIDs
    f, s = fetch_missing(db, m, box, server_uids[-quick:])
    fetched += f; skipped += s
    if progress and f:
        log(f"{box}: quick-seeded {f} recent message(s)")

    # 2. resumable backfill over the contiguous UID range
    if full and server_uids:
        top = server_uids[-1]
        while cursor < top:
            lo, hi = cursor + 1, cursor + batch
            chunk = [u for u in server_uids if lo <= u <= hi]
            f, s = fetch_missing(db, m, box, chunk)
            fetched += f; skipped += s
            cursor = hi
            db.execute(
                "UPDATE sync_state SET backfill_cursor=?, uidvalidity=?, uidnext=?, synced_at=? "
                "WHERE mailbox=?",
                (cursor, st["uidvalidity"], st["uidnext"], int(time.time()), box))
            db.commit()
            if progress:
                log(f"{box}: backfilled UID range ..{hi} "
                    f"(+{f} new, {cached_count(db, box)} cached total)")

    # 3. flags reconcile (explicit sync only)
    changed = reconcile_flags(db, m, box)

    # 4. Bcc for rows cached before Bcc support (explicit sync only)
    bcc_found = backfill_bcc(db, m, box, progress=progress)
    db.execute(
        "UPDATE sync_state SET uidnext=?, synced_at=? WHERE mailbox=?",
        (st["uidnext"], int(time.time()), box))
    db.commit()
    return {"mailbox": box, "server_messages": st["messages"],
            "cached": cached_count(db, box), "fetched": fetched,
            "already_cached": skipped, "flags_updated": changed,
            "bcc_backfilled": bcc_found,
            "backfill_cursor": cursor, "uidnext": st["uidnext"]}

def implicit_sync(db, box, no_sync):
    """Best-effort incremental sync; never fatal, keeps cache fresh on reads."""
    if no_sync:
        return
    row = get_sync_row(db, box)
    if row and row[3] and time.time() - row[3] < SYNC_STALENESS:
        return
    m = try_connect()
    if m is None:
        return  # Bridge down: serve whatever the cache has
    try:
        st = mailbox_status(m, box)
        if get_sync_row(db, box) is None or get_sync_row(db, box)[0] != st["uidvalidity"]:
            sync_mailbox(db, m, box, full=False, progress=False)
        else:
            m.select(quote_mailbox(box), readonly=True)
            typ, d = m.uid("SEARCH", "ALL")
            server_uids = sorted(int(u) for u in d[0].split()) if d and d[0] else []
            fetch_missing(db, m, box, server_uids[-QUICK_SEED:])
            db.execute("UPDATE sync_state SET uidnext=?, synced_at=? WHERE mailbox=?",
                       (st["uidnext"], int(time.time()), box))
            db.commit()
    finally:
        try:
            m.logout()
        except Exception:
            pass

# ----------------------------------------------------------- command impls

def cmd_setup(args):
    acct = input("Proton account email: ").strip()
    if not acct:
        die("empty account")
    pw = getpass.getpass(f"Bridge password for {acct} (Bridge app > Mailbox details): ")
    if not pw:
        die("empty password")
    r = subprocess.run(
        ["security", "add-generic-password", "-s", KEYCHAIN_SERVICE, "-a", acct,
         "-w", pw, "-U"], capture_output=True, text=True)
    if r.returncode != 0:
        die(f"Keychain store failed: {r.stderr.strip()}")
    os.makedirs(DATA_DIR, exist_ok=True)
    with open(CONFIG_PATH, "w") as f:
        json.dump({"account": acct}, f)
    os.chmod(CONFIG_PATH, 0o600)
    m = connect()
    m.logout()
    log(f"Account '{acct}' configured; password stored in macOS Keychain and "
        f"verified against Bridge.")

def cmd_mailboxes(args):
    db = open_db()
    m = connect()
    typ, boxes = m.list()
    if typ != "OK":
        die("LIST failed")
    out = []
    for b in boxes:
        if not isinstance(b, bytes):
            continue
        mm = re.match(rb"\(([^)]*)\)\s+\"[^\"]*\"\s+(.*)$", b)
        if not mm:
            continue
        attrs = mm.group(1).decode(errors="replace")
        name = mm.group(2).decode(errors="replace").strip('"')
        entry = {"mailbox": name, "attributes": attrs}
        if "\\Noselect" not in attrs:
            try:
                st = mailbox_status(m, name)
                entry["messages"] = st["messages"]
            except SystemExit:
                entry["messages"] = None
            entry["cached"] = cached_count(db, name)
        out.append(entry)
    m.logout()
    emit(out)

def cmd_list(args):
    db = open_db()
    implicit_sync(db, args.mailbox, args.no_sync)
    use_cache = (not args.live) and cached_count(db, args.mailbox) > 0
    if use_cache:
        sql = ("SELECT uid, date, from_addr, to_addr, bcc, subject, flags FROM messages "
               "WHERE mailbox=?")
        params = [args.mailbox]
        if args.unseen:
            sql += " AND flags NOT LIKE '%\\Seen%'"
        sql += " ORDER BY uid DESC LIMIT ?"
        params.append(args.limit)
        rows = [{"uid": r[0], "date": iso(r[1]), "from": r[2], "to": r[3],
                 "bcc": r[4], "subject": r[5], "flags": r[6], "source": "cache"}
                for r in db.execute(sql, params)]
        emit({"mailbox": args.mailbox, "source": "cache", "count": len(rows),
              "messages": rows})
        return
    m = connect()
    m.select(quote_mailbox(args.mailbox), readonly=True)
    typ, d = m.uid("SEARCH", "UNSEEN" if args.unseen else "ALL")
    uids = sorted(int(u) for u in d[0].split()) if d and d[0] else []
    latest = uids[-args.limit:][::-1]
    rows = fetch_headers(m, latest)
    m.logout()
    for r in rows:
        r["source"] = "live"
    emit({"mailbox": args.mailbox, "source": "live", "count": len(rows),
          "messages": rows})

def render_message(box, uid, rec, flags, max_chars):
    body, source = rec["body_text"], "text"
    if not body and rec["body_html"]:
        body, source = html_to_text(rec["body_html"]), "html-stripped"
    truncated = False
    if max_chars and len(body) > max_chars:
        body = body[:max_chars]
        truncated = True
    return {
        "mailbox": box, "uid": uid,
        "date": iso(rec["date"]), "from": rec["from_addr"], "to": rec["to_addr"],
        "cc": rec["cc"], "bcc": rec["bcc"], "subject": rec["subject"], "flags": flags,
        "body_source": source, "truncated": truncated,
        "attachments": json.loads(rec["attachments"] or "[]"),
        "body": body,
    }

def cmd_read(args):
    if args.raw:
        m = connect()
        m.select(quote_mailbox(args.mailbox), readonly=True)
        for uid, flags, raw in fetch_full(m, [args.uid]):
            sys.stdout.buffer.write(raw)
            m.logout()
            return
        m.logout()
        die(f"UID {args.uid} not found in {args.mailbox}")
    db = open_db()
    implicit_sync(db, args.mailbox, args.no_sync)
    row = db.execute(
        "SELECT message_id, date, from_addr, to_addr, cc, subject, flags, size,"
        " body_text, body_html, attachments, bcc FROM messages WHERE mailbox=? AND uid=?",
        (args.mailbox, args.uid)).fetchone()
    if row is not None:
        rec = {"date": row[1], "from_addr": row[2], "to_addr": row[3], "cc": row[4],
               "bcc": row[11], "subject": row[5], "body_text": row[8],
               "body_html": row[9], "attachments": row[10]}
        out = render_message(args.mailbox, args.uid, rec, row[6], args.max_chars)
        out["source"] = "cache"
        emit(out)
        return
    # cache miss -> live fetch, cache it, render
    m = connect()
    m.select(quote_mailbox(args.mailbox), readonly=True)
    for uid, flags, raw in fetch_full(m, [args.uid]):
        rec = parse_message(raw)
        insert_record(db, args.mailbox, rec, uid, flags)
        db.commit()
        m.logout()
        out = render_message(args.mailbox, uid, rec, flags, args.max_chars)
        out["source"] = "live"
        emit(out)
        return
    m.logout()
    die(f"UID {args.uid} not found in {args.mailbox}")

def cmd_search(args):
    db = open_db()
    if args.substring and args.live:
        die("--substring scans the local cache and cannot be combined with --live")
    if not args.live:
        implicit_sync(db, args.mailbox, args.no_sync)
        if args.substring:
            return search_substring(db, args)
        if cached_count(db, args.mailbox) > 0:
            return search_fts(db, args)
        log("pmail: cache empty for this mailbox; falling back to --live search")
    m = connect()
    m.select(quote_mailbox(args.mailbox), readonly=True)
    crit = []
    if args.unseen:
        crit.append("UNSEEN")
    if args.sender:
        crit += ["FROM", f'"{args.sender}"']
    if args.subject:
        crit += ["SUBJECT", f'"{args.subject}"']
    if args.since:
        crit += ["SINCE", args.since]
    for w in args.words:
        crit += ["TEXT", f'"{w}"']
    if not crit:
        die("search needs at least one word or filter")
    typ, d = m.uid("SEARCH", *crit)
    if typ != "OK":
        die(f"SEARCH failed: {d}")
    uids = sorted(int(u) for u in d[0].split()) if d and d[0] else []
    latest = uids[-args.limit:][::-1]
    rows = fetch_headers(m, latest)
    m.logout()
    emit({"mailbox": args.mailbox, "source": "live", "total_hits": len(uids),
          "count": len(rows), "messages": rows})

def search_fts(db, args):
    where, params = ["mail_fts MATCH ?"], [args.query]
    where.append("m.mailbox=?"); params.append(args.mailbox)
    if args.sender:
        where.append("m.from_addr LIKE ?"); params.append(f"%{args.sender}%")
    if args.since:
        try:
            ts = int(datetime.fromisoformat(args.since).replace(tzinfo=timezone.utc).timestamp())
            where.append("m.date >= ?"); params.append(ts)
        except ValueError:
            die(f"--since must be ISO date (e.g. 2026-01-01), got '{args.since}'")
    if args.unseen:
        where.append("m.flags NOT LIKE '%\\Seen%'")
    # rank in a CTE first (CROSS JOIN pins scan order: FTS first, rowid probes),
    # then compute the expensive snippet() only for the rows that survive LIMIT
    sql = f"""
      WITH top AS (
        SELECT m.rowid AS rid, bm25(mail_fts, 10.0, 5.0, 1.0, 1.0, 1.0) AS r
        FROM mail_fts CROSS JOIN messages m ON m.rowid = mail_fts.rowid
        WHERE {' AND '.join(where)}
        ORDER BY r LIMIT ?)
      SELECT m.uid, m.date, m.from_addr, m.subject, m.flags,
             snippet(mail_fts, 3, '>>>', '<<<', '...', 24), top.r
      FROM top JOIN messages m ON m.rowid = top.rid
      JOIN mail_fts ON mail_fts.rowid = top.rid
      ORDER BY top.r"""
    params.append(args.limit)
    try:
        rows = db.execute(sql, params).fetchall()
    except sqlite3.OperationalError:
        # not a valid FTS5 query: treat words as an AND of quoted terms
        terms = args.query.split()
        if not terms:
            die("empty search query")
        params[0] = " AND ".join('"' + t.replace('"', '') + '"' for t in terms)
        try:
            rows = db.execute(sql, params).fetchall()
        except sqlite3.OperationalError as e:
            die(f"search failed: {e}")
    out = [{"uid": r[0], "date": iso(r[1]), "from": r[2], "subject": r[3],
            "flags": r[4],
            "snippet": INVISIBLES_RE.sub("", re.sub(r"\s+", " ", r[5] or "")).strip(),
            "rank": round(r[6], 3)} for r in rows]
    emit({"mailbox": args.mailbox, "source": "cache-fts", "query": args.query,
          "count": len(out), "messages": out})

# Column per --field name. `attachment` matches the JSON-encoded attachment
# list (filenames and MIME types). `body` is the slow one: a full scan of
# every cached body.
SUBSTRING_FIELDS = {
    "subject": "m.subject",
    "from": "m.from_addr",
    "to": "m.to_addr",
    "bcc": "m.bcc",
    "attachment": "m.attachments",
    "body": "m.body_text",
}
SUBSTRING_FAST_FIELDS = ["subject", "from", "to", "bcc", "attachment"]

# Covering index so a metadata-only substring scan never touches the table
# rows (which carry multi-KB bodies). Built lazily on first --substring use.
META_INDEX_NAME = "messages_meta_v2"   # v2 adds bcc
META_INDEX = f"""CREATE INDEX IF NOT EXISTS {META_INDEX_NAME} ON messages
  (mailbox, date, uid, from_addr, to_addr, bcc, subject, flags, attachments)"""

def ensure_meta_index(db):
    if db.execute("SELECT 1 FROM sqlite_master WHERE type='index' AND name=?",
                  (META_INDEX_NAME,)).fetchone():
        return
    log("pmail: building metadata index for substring search (one-off, may take a minute)")
    db.execute("DROP INDEX IF EXISTS messages_meta")
    db.execute(META_INDEX)
    db.commit()

def like_pattern(text):
    """Escape LIKE metacharacters so the user's text matches literally."""
    esc = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
    return f"%{esc}%"

def substring_snippet(text, needle, width=80):
    """Case-insensitive context window around the first match of needle."""
    if not text:
        return ""
    i = text.lower().find(needle.lower())
    if i < 0:
        return ""
    lo, hi = max(0, i - width // 2), min(len(text), i + len(needle) + width // 2)
    s = ("..." if lo > 0 else "") + text[lo:hi] + ("..." if hi < len(text) else "")
    return INVISIBLES_RE.sub("", re.sub(r"\s+", " ", s)).strip()

def search_substring(db, args):
    """Case-insensitive substring scan (SQL LIKE) over cached columns.

    Unlike FTS this matches inside tokens ("INV-2026-0042", part of an
    attachment filename, a domain fragment). It cannot use the FTS index:
    metadata fields scan in well under a second on an ~80k-message cache,
    but `body` reads every cached body and can take tens of seconds."""
    needle = args.query
    if not needle:
        die("--substring needs the text to look for")
    fields = args.field or SUBSTRING_FAST_FIELDS
    if "all" in fields:
        fields = list(SUBSTRING_FIELDS)
    fields = list(dict.fromkeys(fields))  # dedupe, keep order
    if "body" in fields:
        log(f"pmail: substring scan includes body text over "
            f"{cached_count(db, args.mailbox)} cached message(s); this may take a while")
    else:
        ensure_meta_index(db)
    pattern = like_pattern(needle)
    match = " OR ".join(f"{SUBSTRING_FIELDS[f]} LIKE ? ESCAPE '\\'" for f in fields)
    where, params = [f"({match})"], [pattern] * len(fields)
    where.append("m.mailbox=?"); params.append(args.mailbox)
    if args.sender:
        where.append("m.from_addr LIKE ?"); params.append(f"%{args.sender}%")
    if args.since:
        try:
            ts = int(datetime.fromisoformat(args.since).replace(tzinfo=timezone.utc).timestamp())
            where.append("m.date >= ?"); params.append(ts)
        except ValueError:
            die(f"--since must be ISO date (e.g. 2026-01-01), got '{args.since}'")
    if args.unseen:
        where.append("m.flags NOT LIKE '%\\Seen%'")
    sql = f"""
      SELECT m.uid, m.date, m.from_addr, m.to_addr, m.bcc, m.subject, m.flags,
             m.attachments, {'m.body_text' if 'body' in fields else 'NULL'}
      FROM messages m
      WHERE {' AND '.join(where)}
      ORDER BY m.date DESC, m.uid DESC LIMIT ?"""
    params.append(args.limit)
    t0 = time.time()
    rows = db.execute(sql, params).fetchall()
    out = []
    for uid, date, from_addr, to_addr, bcc, subject, flags, attachments, body in rows:
        atts = json.loads(attachments or "[]")
        matched = []
        nl = needle.lower()
        if "subject" in fields and nl in (subject or "").lower():
            matched.append("subject")
        if "from" in fields and nl in (from_addr or "").lower():
            matched.append("from")
        if "to" in fields and nl in (to_addr or "").lower():
            matched.append("to")
        if "bcc" in fields and nl in (bcc or "").lower():
            matched.append("bcc")
        if "attachment" in fields and any(
                nl in (a.get("name", "") + " " + a.get("mime", "")).lower() for a in atts):
            matched.append("attachment")
        if "body" in fields and body and nl in body.lower():
            matched.append("body")
        row = {"uid": uid, "date": iso(date), "from": from_addr, "subject": subject,
               "flags": flags, "matched": matched,
               "attachments": [{"index": a.get("index"), "name": a.get("name"),
                                "mime": a.get("mime")} for a in atts]}
        if "body" in matched:
            row["snippet"] = substring_snippet(body, needle)
        out.append(row)
    emit({"mailbox": args.mailbox, "source": "cache-substring", "query": needle,
          "fields": fields, "scanned": cached_count(db, args.mailbox),
          "elapsed_s": round(time.time() - t0, 2),
          "count": len(out), "messages": out})

def cmd_sync(args):
    db = open_db()
    m = connect()
    if args.all:
        typ, boxes = m.list()
        targets = []
        for b in boxes or []:
            if isinstance(b, bytes):
                mm = re.match(rb"\(([^)]*)\)\s+\"[^\"]*\"\s+(.*)$", b)
                if mm and b"\\Noselect" not in mm.group(1):
                    targets.append(mm.group(2).decode(errors="replace").strip('"'))
        if len(targets) > 1 and "All Mail" in targets and args.skip_all_mail:
            targets.remove("All Mail")
        # backfill the biggest (All Mail) last so smaller boxes finish first
        targets.sort(key=lambda t: (t == "All Mail", t))
    else:
        targets = [args.mailbox]
    results = []
    for box in targets:
        m.select(quote_mailbox(box), readonly=True)
        results.append(sync_mailbox(db, m, box, full=args.full, batch=args.batch))
    m.logout()
    emit({"synced": results})

def cmd_status(args):
    db = open_db()
    rows = []
    for box, uidvalidity, cursor, uidnext, synced_at in db.execute(
            "SELECT mailbox, uidvalidity, backfill_cursor, uidnext, synced_at "
            "FROM sync_state ORDER BY mailbox"):
        rows.append({
            "mailbox": box, "cached": cached_count(db, box),
            "server_messages": (uidnext - 1) if uidnext else None,
            "backfill_complete": bool(uidnext and cursor >= uidnext - 1),
            "backfill_cursor": cursor, "uidnext": uidnext,
            "last_sync": iso(synced_at),
        })
    db_size = os.path.getsize(DB_PATH) if os.path.exists(DB_PATH) else 0
    attach = []
    if os.path.isdir(ATTACH_DIR):
        attach = os.listdir(ATTACH_DIR)
    emit({"db_path": DB_PATH, "db_size_mb": round(db_size / 1e6, 1),
          "mailboxes": rows, "attachments_saved": len(attach)})

def cmd_save_attach(args):
    db = open_db()
    os.makedirs(ATTACH_DIR, exist_ok=True)
    m = connect()
    m.select(quote_mailbox(args.mailbox), readonly=True)
    for uid, flags, raw in fetch_full(m, [args.uid]):
        msg = BytesParser(policy=policy.default).parsebytes(raw)
        idx = 0
        for part in msg.walk():
            if part.get_content_maintype() == "multipart":
                continue
            filename = part.get_filename()
            if part.get_content_disposition() == "attachment" or filename:
                idx += 1
                if idx == args.index:
                    payload = part.get_payload(decode=True)
                    if payload is None:
                        m.logout()
                        die(f"attachment {args.index} has no decodable payload")
                    safe = re.sub(r"[^\w.\-]+", "_", filename or f"attachment-{idx}")
                    path = os.path.join(ATTACH_DIR,
                                        f"{args.mailbox.replace('/', '_')}-{uid}-{idx}-{safe}")
                    with open(path, "wb") as f:
                        f.write(payload)
                    m.logout()
                    emit({"saved": path, "name": filename, "mime": part.get_content_type(),
                          "size": len(payload)})
                    return
        m.logout()
        die(f"message UID {args.uid} has only {idx} attachment(s)")
    m.logout()
    die(f"UID {args.uid} not found in {args.mailbox}")

# --------------------------------------------------------------------- CLI

def build_parser():
    p = argparse.ArgumentParser(
        prog="pmail",
        description="Read ProtonMail via local Bridge IMAP. Read-only. JSON on stdout.")
    sub = p.add_subparsers(dest="cmd", required=True)

    sp = sub.add_parser("setup", help="store Bridge password in macOS Keychain")
    sp.set_defaults(fn=cmd_setup)

    sp = sub.add_parser("mailboxes", help="list folders/labels with counts")
    sp.set_defaults(fn=cmd_mailboxes)

    sp = sub.add_parser("list", help="list messages (default: INBOX, cache-first)")
    sp.add_argument("mailbox", nargs="?", default="INBOX")
    sp.add_argument("--limit", type=int, default=DEFAULT_LIMIT)
    sp.add_argument("--unseen", action="store_true")
    sp.add_argument("--live", action="store_true", help="bypass cache, query Bridge")
    sp.add_argument("--no-sync", action="store_true", help="skip implicit incremental sync")
    sp.set_defaults(fn=cmd_list)

    sp = sub.add_parser("read", help="read one message by UID (cache-first)")
    sp.add_argument("uid", type=int)
    sp.add_argument("--mailbox", default="INBOX")
    sp.add_argument("--raw", action="store_true", help="dump untouched RFC822 to stdout")
    sp.add_argument("--max-chars", type=int, default=20000, help="0 = no limit")
    sp.add_argument("--no-sync", action="store_true")
    sp.set_defaults(fn=cmd_read)

    sp = sub.add_parser("search", help="full-text search (FTS5 cache) or --live IMAP search")
    sp.add_argument("words", nargs="*", help="keywords (AND-ed); quotes/phrases passed to FTS5")
    sp.add_argument("--mailbox", default="All Mail")
    sp.add_argument("--from", dest="sender")
    sp.add_argument("--subject")
    sp.add_argument("--since", help="ISO date, e.g. 2026-01-01")
    sp.add_argument("--unseen", action="store_true")
    sp.add_argument("--limit", type=int, default=DEFAULT_LIMIT)
    sp.add_argument("--substring", action="store_true",
                    help="case-insensitive substring (LIKE) scan of the cache instead of "
                         "FTS; matches inside tokens, e.g. part of an attachment filename")
    sp.add_argument("--field", action="append",
                    choices=[*SUBSTRING_FIELDS, "all"],
                    help="with --substring: column(s) to scan (repeatable). Default: "
                         "subject, from, to, bcc, attachment (fast). 'body' or 'all' scans "
                         "every cached body and is slow")
    sp.add_argument("--live", action="store_true")
    sp.add_argument("--no-sync", action="store_true")
    sp.set_defaults(fn=cmd_search)

    sp = sub.add_parser("sync", help="sync mailbox(es) into the local cache")
    sp.add_argument("--mailbox", default="INBOX")
    sp.add_argument("--all", action="store_true", help="sync every folder/label")
    sp.add_argument("--skip-all-mail", action="store_true",
                    help="with --all: skip the 'All Mail' virtual mailbox (it duplicates the others)")
    sp.add_argument("--full", action="store_true", help="run/resume full backfill")
    sp.add_argument("--batch", type=int, default=BACKFILL_BATCH)
    sp.set_defaults(fn=cmd_sync)

    sp = sub.add_parser("status", help="cache state per mailbox")
    sp.set_defaults(fn=cmd_status)

    sp = sub.add_parser("save-attach", help="download attachment N of message UID")
    sp.add_argument("uid", type=int)
    sp.add_argument("index", type=int, help="attachment index from `read` output (1-based)")
    sp.add_argument("--mailbox", default="INBOX")
    sp.set_defaults(fn=cmd_save_attach)
    return p

def main():
    args = build_parser().parse_args()
    if args.cmd == "search":
        args.query = " ".join(args.words)
        if not args.live and not args.query and not (args.sender or args.subject):
            die("search needs at least one word (cached search is text-based)")
        if args.field and not args.substring:
            die("--field only applies with --substring")
    args.fn(args)

if __name__ == "__main__":
    main()
