#!/usr/bin/env bash

set -e
set -o nounset
set -o pipefail

FZF_DEFAULT_OPTS=${FZF_DEFAULT_OPTS:-""}
THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename $THIS_FILE)
THIS=${THIS:-$LOG_LABEL}
LOG_FILE=${LOG_FILE:-$LOG_LABEL.log}
SCRIPTS=${SCRIPTS:-$HOME/.local/scripts}
XDG_CONFIG_HOME=${XDG_CONFIG_HOME}

usage() {
  cat <<EOF

A fuzzy finder to launch utility applications / scripts from a single menu.

USAGE:

  $ $THIS [OPTIONS]

OPTIONS:

  -c | --config <file>:      Set the location of the configuration file (default: XDG_CONFIG_HOME/utils-launcher/config.json)
  -l | --launch:             Launches in a new terminal window.

EOF
}

window_class="com.ghostty.$THIS"
window_padding_x="2"

config_file=""
launch_flag="0"

rows=()
invocation_id=${RANDOM}

while [[ $# -gt 0 ]]; do
  if [[ $1 == "-c" ]] || [[ $1 == "--config" ]]; then
    shift
    config_file="$1"
  elif [[ $1 == "-l" ]] || [[ $1 == "--launch" ]]; then
    launch_flag="1"
  fi
  shift
done

log() {
  logging log --source "$THIS_FILE" "$@"
}

launch() {
  ghostty --class=$window_class --window-padding-x=$window_padding_x \
    --keybind="ctrl+c=quit" \
    -e ${BASH_SOURCE[0]} --config $config_file
}

footer() {
  cat <<'EOF'
   __  ______________   _____
  / / / /_  __/  _/ /  / ___/
 / / / / / /  / // /   \__ \ 
/ /_/ / / / _/ // /______/ / 
\____/ /_/ /___/_____/____/  
                             
EOF
}

generate_rows() {
  readarray -t names <<<"$(echo "$1" | jq -r '.[] | .name')"
  readarray -t execs <<<"$(echo "$1" | jq -r '.[] | .exec')"

  for i in "${!names[@]}"; do
    rows+=("${execs[i]}|${names[i]}")
  done
}

################################################################################
# MAIN
################################################################################

# Setup logging file and label.
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

if [[ -z $XDG_CONFIG_HOME ]]; then
  log "XDG_CONFIG_HOME not set"
  log "using ~/.config"
  XDG_CONFIG_HOME=$HOME/.config
fi

if [[ -z $config_file ]]; then
  log "No config file set."
  log "Using ~/.config/utils-launcher/config.json"
  config_file="$XDG_CONFIG_HOME/utils-launcher/config.json"
fi

if [[ $launch_flag == "1" ]]; then
  launch && exit 0
fi

if [[ ! -f $config_file ]]; then
  log "[ERROR]: no config file set" && exit 1
fi

file_data=$(cat $config_file)

# Setup colors before calling fzf.
[[ -z $FZF_DEFAULT_OPTS ]] &&
  [[ -f $SCRIPTS/catppuccin-colors ]] &&
  source $SCRIPTS/catppuccin-colors

generate_rows "$file_data"
sel=$(
  printf "%s\n" "${rows[@]}" |
    fzf --style=full --footer="$(footer)" --with-nth=2 --delimiter='|' \
      --preview-label='[ Command ]' \
      --preview="$SCRIPTS/hypr/utils/fzf/preview-stats utils {2} $config_file" \
      --preview-window='down,30%'
)

log "Selection: $sel"

if [[ -n "$sel" ]]; then
  # Parse the exec command for the selection.
  exec_cmd=${sel%%|*}

  log "Exec: '$exec_cmd'"
  if [[ -z $exec_cmd ]]; then
    log "[ERROR]: Command is empty." && exit 1
  fi
  eval exec uwsm app -- "$exec_cmd"
else
  log "No selection."
fi
