#!/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_uncached() (
  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" \; \
    show-options -g prefix \; \
    show-options -g prefix2 \; \
    list-keys -aN -T prefix -P "prefix" \; \
    list-keys -aN -T root -P "root" \; \
    list-keys -aN -T copy-mode-vi -P "copy-mode-vi" | awk '
function key_part_text(part, is_modifier, part_count) {
  gsub(/^\\/, "", part)

  if (is_modifier && part == "C") return "CTRL"
  if (is_modifier && part == "M") return "ALT"
  if (is_modifier && part == "S") return "SHIFT"
  if (part == "Space") return "SPACE"
  if (part == "BSpace") return "BACKSPACE"
  if (part == "BTab") return "SHIFT + TAB"
  if (part == "PPage") return "PAGE UP"
  if (part == "NPage") return "PAGE DOWN"
  if (part == "DC") return "DELETE"
  if (part == "IC") return "INSERT"
  if (part_count == 1 && part ~ /^[a-z]$/) return part

  return toupper(part)
}

function key_text(key, parts, count, i, part, text) {
  gsub(/\\/, "", key)
  count = split(key, parts, "-")
  text = ""

  for (i = 1; i <= count; i++) {
    part = key_part_text(parts[i], i < count, count)
    text = text (text == "" ? "" : " + ") part
  }

  return text
}

function table_text(table) {
  if (table == "copy-mode-vi") return "COPY MODE"
  if (table == "copy-mode") return "COPY MODE"
  if (table == "prefix") return "PREFIX"

  gsub(/-/, " ", table)
  return toupper(table)
}

$1 == "prefix" && NF == 2 { prefix = $2; next }
$1 == "prefix2" && NF == 2 { prefix2 = $2; next }

{
  if (!header_printed) {
    prefix_description = key_text(prefix)

    if (prefix2 != "" && prefix2 != "None") {
      prefix_description = prefix_description " / " key_text(prefix2)
    }

    printf "%-32s → %s\n", "PREFIX", prefix_description
    header_printed = 1
  }

  table = $1
  key = $2
  note = $0
  sub(/^[^ ]+ +[^ ]+ +/, "", note)

  if (table == "root") {
    combo = key_text(key)
  } else {
    combo = table_text(table) " + " key_text(key)
  }

  printf "%-32s → %s\n", combo, note
}'
)

# Skip caching when the config dynamically sources other files, uses tmux
# preprocessor directives, or runs shell conditionals at load time (including
# commands chained after an unescaped semicolon), so external edits are never
# hidden behind a cache.
config_cacheable() {
  awk '
    /^[[:space:]]*#/ || /^[[:space:]]*$/ { next }
    /^[[:space:]]*%/ { exit 1 }
    {
      line = $0
      gsub(/\\;/, "\001", line)
      n = split(line, cmds, ";")
      for (i = 1; i <= n; i++) {
        cmd = cmds[i]
        sub(/^[[:space:]]+/, "", cmd)
        if (cmd ~ /^(bind|bind-key)[[:space:]]/) continue
        if (cmd ~ /^(source(-file)?|if(-shell)?|run(-shell)?)[[:space:]]/) exit 1
      }
    }
  ' "$config_file"
}

output_keybindings() {
  if ! config_cacheable; then
    output_keybindings_uncached
    return
  fi

  local cache_dir cache_name cache_file hash _ tmp_file
  cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/omarchy"
  read -r hash _ < <(
    {
      printf 'v1\n'
      tmux -V 2>/dev/null
      cat "$config_file"
    } | sha256sum
  )
  cache_name="tmux-keybindings-$hash.records"
  cache_file="$cache_dir/$cache_name"

  if [[ -s $cache_file ]] && cat "$cache_file" 2>/dev/null; then
    return 0
  elif mkdir -p "$cache_dir" 2>/dev/null && tmp_file=$(mktemp "$cache_dir/tmux-keybindings.XXXXXX"); then
    if output_keybindings_uncached >"$tmp_file" && [[ -s $tmp_file ]]; then
      cat "$tmp_file"
      mv -f "$tmp_file" "$cache_file"
      find "$cache_dir" -maxdepth 1 -type f -name 'tmux-keybindings-*.records' ! -name "$cache_name" -mmin +1 -delete 2>/dev/null || true
    else
      rm -f "$tmp_file"
      return 1
    fi
  else
    output_keybindings_uncached
  fi
}

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

records=$(output_keybindings)

monitor_height=$(hyprctl monitors 2>/dev/null | awk '
  /^Monitor / { h = "" }
  /^[[:space:]]+[0-9]+x[0-9]+@/ { split($1, dims, /[x@]/); h = dims[2] }
  /^[[:space:]]+focused:[[:space:]]*yes/ { print h; exit }
')

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 "$(omarchy-i18n keybindings.tmuxTitle)" -- --width 800 --height "$menu_height" >/dev/null || true
