#!/bin/bash
# Open a neomutt:// link in neomutt via notmuch
# Usage: open-message-link [--current] neomutt://message-id
#   --current: Open in current terminal (for nvim integration)
#   Without flag: Opens in Ghostty on workspace 8 (like open-mail)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
set -euo pipefail

open_in_current=false
if [[ ${1:-} == "--current" ]]; then
    open_in_current=true
    shift
fi

url="${1:-}"
if [[ -z $url ]]; then
    echo "Usage: open-message-link [--current] neomutt://message-id" >&2
    exit 1
fi

# Extract message ID from URL
message_id="${url#neomutt://}"
notmuch_url="notmuch://?query=id:${message_id}"

if $open_in_current; then
    exec neomutt -f "$notmuch_url"
else
    # Create a temp script with PATH setup embedded
    tmpscript=$(mktemp /tmp/open-mail-XXXXXX.sh)
    cat >"$tmpscript" <<EOF
#!/bin/bash
export PATH="/etc/profiles/per-user/\$USER/bin:/run/current-system/sw/bin:\$PATH"
export NOTMUCH_CONFIG="\$HOME/.config/notmuch/config"
rm -f "$tmpscript"
exec neomutt -f '$notmuch_url'
EOF
    chmod +x "$tmpscript"

    if [[ "$(uname)" == "Darwin" ]]; then
        aerospace workspace 8
        open -na Ghostty --args --title="Mail" -e "$tmpscript"
    else
        # Linux (i3/sway)
        if command -v swaymsg &>/dev/null; then
            swaymsg workspace 8
            ghostty --title="Mail" -e "$tmpscript" &
        elif command -v i3-msg &>/dev/null; then
            i3-msg workspace 8
            ghostty --title="Mail" -e "$tmpscript" &
        else
            rm -f "$tmpscript"
            exec neomutt -f "$notmuch_url"
        fi
    fi
fi
