#!/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
    if [[ "$(uname)" == "Darwin" ]]; then
        aerospace workspace 8
        open -na Ghostty --args -e "$SCRIPT_DIR/path-shim" "$SCRIPT_DIR/neomutt-open-message" "$message_id"
    else
        # Linux (i3/sway)
        if command -v swaymsg &>/dev/null; then
            swaymsg workspace 8
            ghostty -e neomutt -e "push \"<vfolder-from-query>id:${message_id}<enter><display-message>\"" &
        elif command -v i3-msg &>/dev/null; then
            i3-msg workspace 8
            ghostty -e neomutt -e "push \"<vfolder-from-query>id:${message_id}<enter><display-message>\"" &
        else
            exec neomutt -f "$notmuch_url"
        fi
    fi
fi
