#!/bin/bash

# omarchy:summary=Display annotated Tmux keybindings using an interactive search menu.
# omarchy:args=[--print|-p] [--config <path>]

print_only=false
config_file="${TMUX_CONF:-$HOME/.config/tmux/tmux.conf}"

while (($#)); do
  case "$1" in
    --print|-p)
      print_only=true
      ;;
    --config)
      shift
      config_file="$1"
      ;;
    *)
      config_file="$1"
      ;;
  esac

  shift
done

if [[ ! -f $config_file ]]; then
  default_config="$OMARCHY_PATH/config/tmux/tmux.conf"

  if [[ -f $default_config ]]; then
    config_file="$default_config"
  else
    echo "Tmux config not found: $config_file" >&2
    exit 1
  fi
fi

output_keybindings() (
  set -o pipefail
  socket_dir=$(mktemp -d)
  socket="$socket_dir/tmux"
  trap 'tmux -S "$socket" kill-server >/dev/null 2>&1 || true; rm -f "$socket"; rmdir "$socket_dir" 2>/dev/null || true' EXIT
  tmux -S "$socket" -f /dev/null start-server \; \
    unbind-key -a -T prefix \; \
    unbind-key -a -T root \; \
    unbind-key -a -T copy-mode \; \
    unbind-key -a -T copy-mode-vi \; \
    source-file "$config_file" \; \
    list-keys -aN -T prefix \; \
    list-keys -aN -T root -P "" \; \
    list-keys -aN -T copy-mode-vi -P "copy-mode-vi" | sed 's/^ //'
)

if [[ $print_only == "true" ]]; then
  output_keybindings
  exit 0
fi

records=$(output_keybindings)

monitor_height=$(hyprctl monitors -j 2>/dev/null | jq -r '.[] | select(.focused == true) | .height' 2>/dev/null)

if [[ ! $monitor_height =~ ^[0-9]+$ ]] || ((monitor_height <= 0)); then
  monitor_height=900
fi

menu_height=$((monitor_height * 40 / 100))
printf '%s\n' "$records" | omarchy-menu-select 'Tmux keybindings' -- --width 800 --height "$menu_height" >/dev/null || true
