#!/bin/sh
set -eu

sessions="$(tmux list-sessions -F '#S' 2>/dev/null || true)"
[ -n "${sessions}" ] || exit 0

walker_pick_session() {
  if command -v walker >/dev/null 2>&1; then
    walker -d -p 'tmux sessions:'
  fi
}

rofi_pick_session() {
    if command -v rofi >/dev/null 2>&1; then
        rofi -dmenu -p 'tmux sessions:'
    fi
}

chosen="$(printf '%s\n' "$sessions" | rofi_pick_session)"

[ -n "$chosen" ] || exit 0

if [ "${TMUX-}" ]; then
  exec tmux switch-client -t "${chosen}"
fi

client_tty="$(
  tmux list-clients -F '#{client_tty} #{client_termname}' 2>/dev/null \
  | awk '$2 ~ /ghostty/ { print $1; exit }' || true
)"

if [ -n "${client_tty}" ]; then
  # switch that client to the chosen session
  tmux switch-client -c "${client_tty}" -t "${chosen}"
  address=$(hyprctl clients -j | jq -r "to_entries | .[] | select(.value.class == \"com.mitchellh.ghostty\") | \"\(.value.address)\"")
  workspace=$(hyprctl clients -j | jq -r ".[] | select(.address == \"$address\") | \"(.workspace.id)\"")
  hyprctl dispatch focusworkspaceoncurrentmonitor "$workspace"
  hyprctl dispatch focuswindow "address:$address"
  exit 0
fi


