#!/bin/bash
# mail-compose — :menu picker for aerc's :compose (runs INSIDE aerc's popover)
# Bound to `M`:  M = :menu -t Compose -c 'mail-compose' :compose<Enter>
#
# Flow (each step labelled, each skippable with Esc):
#   [1/5] account   → switches the account tab via IPC (:change-tab)
#   [2/5] from/alias (identities parsed from accounts.conf)
#   [3/5] To        (fzf --multi over abook)
#   [4/5] Cc
#   [5/5] Bcc
# aerc appends our stdout to `:compose` (xargs-style, quotes preserved):
#   :compose -H "From: ..." -H "To: ..." -H "Cc: ..." -H "Bcc: ..."
# Nothing picked → bare :compose (empty message).

set -u

AERC_ACCOUNTS="$HOME/.config/aerc/accounts.conf"
DRY_RUN=0
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1

# ---------- accounts & identities from accounts.conf ----------
mapfile -t ACCOUNTS < <(awk '/^\[/{print substr($0,2,index($0,"]")-2)}' "$AERC_ACCOUNTS")

_acct_field() { # $1=account $2=field-regex → value after '='
    awk -v a="$1" -v f="$2" '/^\[/{sec=substr($0,2,index($0,"]")-2); next}
        sec==a && $0 ~ "^" f "[ \\t]*=" {print; exit}' "$AERC_ACCOUNTS"
}

# print "Name <email>" identity lines for one account (default From first, then aliases)
identities() {
    local acct="$1" from_line name from_addr
    from_line=$(_acct_field "$acct" 'from')
    name=$(printf '%s\n' "$from_line" | sed 's/^[^=]*=[ \t]*//' | sed 's/<.*//' | sed 's/^[ \t"]*//; s/[ \t"]*$//')
    {
        printf '%s\n' "$from_line" | sed 's/^[^=]*=[ \t]*//' | sed 's/.*<//; s/>.*//'
        _acct_field "$acct" 'aliases' | sed 's/^[^=]*=[ \t]*//' | tr ',' '\n'
    } | sed 's/^[ \t]*//; s/[ \t]*$//' | awk -v n="$name" 'NF && !seen[$0]++ {
        if ($0 ~ /</) print
        else if (n != "") print n " <" $0 ">"
        else print
    }'
}

# ---------- contacts from abook ----------
CONTACTS=$(abook --mutt-query "" 2>/dev/null | awk -F'\t' '
    {
        email = $1; name = $2
        if (email == "") next
        gsub(/^[ \t]+|[ \t]+$/, "", email); gsub(/^[ \t]+|[ \t]+$/, "", name)
        if (name == "" || name == email || name ~ /[(),<>"]/) printf "%s\n", email
        else printf "%s <%s>\n", name, email
    }')

# ---------- fzf helpers (clear step labelling) ----------
pick_single() { # $1=prompt $2=header ; input on stdin; echoes selection or empty on Esc
    fzf --reverse --info=inline --height=100% --prompt="$1" --header="$2" 2>/dev/null || true
}
pick_multi() { # $1=prompt $2=header ; input on stdin; echoes comma-joined selection
    local sel
    sel=$(fzf --multi --reverse --info=inline --height=100% --prompt="$1" --header="$2" \
        --bind 'ctrl-space:toggle,ctrl-a:toggle-all' 2>/dev/null) || true
    [ -z "$sel" ] && return 0
    printf '%s' "$sel" | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }'
}

if [ -z "$CONTACTS" ]; then
    echo '-H "To: (no contacts — run mailsync first)"'
    exit 0
fi

# ---------- 1/5: account ----------
account="$(printf '%s\n' "${ACCOUNTS[@]}" \
    | pick_single 'account> ' '▸ 1/5 · SEND FROM ACCOUNT · Enter=select · Esc=keep current')"

# switch the account tab so :compose uses the right outgoing transport
if [ -n "$account" ] && [ "$DRY_RUN" = "0" ]; then
    aerc ":change-tab $account" >/dev/null 2>&1
    sleep 0.2
fi

# ---------- 2/5: from/alias ----------
from=""
if [ -n "$account" ]; then
    from="$(identities "$account" \
        | pick_single 'from/alias> ' "▸ 2/5 · FROM — $account · Enter=select · Esc=account default")"
fi

# ---------- 3/5: To ----------
to="$(printf '%s\n' "$CONTACTS" \
    | pick_multi 'to> ' '▸ 3/5 · TO · type to filter · Tab/Ctrl+Space=mark · Enter=done · Esc=skip')"

# ---------- 4/5: Cc ----------
cc=""
if [ -n "$to" ]; then
    cc="$(printf '%s\n' "$CONTACTS" \
        | pick_multi 'cc> ' '▸ 4/5 · CC · type to filter · Tab/Ctrl+Space=mark · Enter=done · Esc=skip')"
fi

# ---------- 5/5: Bcc ----------
bcc=""
if [ -n "$to" ]; then
    bcc="$(printf '%s\n' "$CONTACTS" \
        | pick_multi 'bcc> ' '▸ 5/5 · BCC · type to filter · Tab/Ctrl+Space=mark · Enter=done · Esc=skip')"
fi

# ---------- output: ONE line — :menu appends it to :compose as ONE command ----------
# (each stdout line = one separate command execution, so -H needs its value on the same line)
out=""
[ -n "$from" ] && out="$out -H \"From: $from\""
[ -n "$to" ]   && out="$out -H \"To: $to\""
[ -n "$cc" ]   && out="$out -H \"Cc: $cc\""
[ -n "$bcc" ]  && out="$out -H \"Bcc: $bcc\""
printf '%s' "$out"