#!/opt/local/bin/bash

# NB: get the absolute path to the directory containing this script
# https://stackoverflow.com/a/246128

script_source="${BASH_SOURCE[0]}"

while [ -h "$script_source" ]; do
  target="$(readlink "$script_source")"
  if [[ $target == /* ]]; then
    script_source="$target"
  else
    script_dir="$( dirname "$script_source" )"
    script_source="$script_dir/$target"
  fi
done

script_dir="$( cd -P "$( dirname "$script_source" )" >/dev/null 2>&1 && pwd )"

# NB: dispatch-aware sourcing. Always source CORE (cheap), then only the module(s)
# the dispatched subcommand needs. Keeps the per-keystroke helper path lean.
# -----------------------------------------
git_fuzzy_dir="/opt/local/libexec/git-fuzzy"

# -- CORE (order is load-bearing: load-configs -> utils -> debug -> core) --
. "$git_fuzzy_dir/lib/load-configs.sh"
. "$git_fuzzy_dir/lib/utils.sh"
. "$git_fuzzy_dir/lib/debug.sh"
. "$git_fuzzy_dir/lib/core.sh"

source_lib() { . "$git_fuzzy_dir/lib/$1"; }

# -- map a `helper <sub>` subcommand to its one extra file (core-resident -> none) --
gf_source_helper() {
  case "$1" in
    preview_resize|preview_shortcuts_header|preview_shortcuts_header_with_inspect|\
    inspect_pager|inspect_diff_renderer)  : ;;                          # live in core.sh
    debounced_reload|valid_fzf_port|reload_token_path|reload_is_current|fzf_post)
                                          source_lib modules/helpers/generic.sh ;;
    branch_*)         source_lib modules/helpers/branch.sh ;;
    diff_checkout_*)  source_lib modules/helpers/diff-checkout.sh ;;    # before diff_*
    diff_direct_*)    source_lib modules/helpers/diff-direct.sh ;;      # before diff_*
    diff_*)           source_lib modules/helpers/diff.sh ;;
    log_*)            source_lib modules/helpers/log.sh ;;
    reflog_*)         source_lib modules/helpers/reflog.sh ;;
    show_*)           source_lib modules/helpers/show.sh ;;
    status_*)         source_lib modules/helpers/status.sh ;;
    stash_*)          source_lib modules/helpers/stash.sh ;;
    pr_*)             source_lib modules/helpers/gh/pr.sh ;;
    *)                : ;;                                              # unknown -> gf_run errors
  esac
}

# -- map a top-level command to its module + transitive deps (mirrors gf_run dispatch) --
gf_source_for() {
  if [ "$1" = 'helper' ]; then
    gf_source_helper "$2"
    return
  fi

  local cmd="$1"
  [ "$cmd" = 'interactive' ] && cmd="$2"   # peel interactive: command is the next arg

  case "$cmd" in
    ''|menu)          source_lib modules/main.sh ;;
    branch)           source_lib snapshot.sh; source_lib modules/branch.sh ;;
    diff)             source_lib modules/diff-direct.sh; source_lib modules/diff.sh ;;
    diff_direct)      source_lib modules/diff-direct.sh ;;
    diff_checkout)    source_lib snapshot.sh; source_lib modules/diff-checkout.sh ;;
    log)              source_lib modules/helpers/generic.sh; source_lib modules/log.sh ;;
    reflog)           source_lib modules/helpers/generic.sh; source_lib modules/reflog.sh ;;
    show)             source_lib modules/helpers/show.sh; source_lib modules/show.sh ;;
    status)           source_lib snapshot.sh; source_lib modules/status.sh ;;
    stash)            source_lib modules/stash.sh ;;
    pr)               source_lib modules/gh/pr.sh ;;
    *)                : ;;                  # unknown -> gf_run emits "not found" using CORE only
  esac
}

gf_source_for "$@"
# -----------------------------------------

# -- Invariants (skipped for helper subprocesses: a live, already-validated parent
# spawns them in-repo with GH_AVAILABLE exported, so re-checking is pure waste) --

if [ "$1" != helper ]; then
  if ! type git >/dev/null 2>&1; then
    # shellcheck disable=2016
    gf_log_error '`git` not found; it is required for `git fuzzy` to work.'
    exit 1
  fi

  if ! gf_is_in_git_repo; then
    gf_log_error "not in git repo"
    exit 1
  fi

  if ! type fzf >/dev/null 2>&1; then
    # shellcheck disable=2016
    gf_log_error '`fzf` not found; it is required for `git fuzzy` to work.'
    exit 1
  fi

  FZF_VERSION="$(fzf --version)"
  MIN_FZF_VERSION="0.71.0"
  if [ "$MIN_FZF_VERSION" != "$(printf '%s\n%s\n' "${FZF_VERSION%% *}" "$MIN_FZF_VERSION" | sort -V | head -n1)" ]; then
    # shellcheck disable=2016
    # shellcheck disable=2016
    gf_log_error '`fzf` '"${MIN_FZF_VERSION}"' or newer is required'
    exit 1
  fi

  # NB: checking for actually _unset_
  # shellcheck disable=2016
  if [ -z "${GH_AVAILABLE+X}" ]; then
    if type gh >/dev/null 2>&1; then
      export GH_AVAILABLE="YES"
      gf_log_debug '`gh` found, enabling GitHub support.'
    else
      export GH_AVAILABLE=""
      gf_log_debug '`gh` not found, disabling GitHub support.'
    fi
  fi
fi

gf_run() {
  COMMAND="$1"
  shift
  if [ "$COMMAND" = 'helper' ]; then
    SUB_COMMAND="$1"
    shift
    FUNC="gf_${COMMAND}_${SUB_COMMAND}"
    PARAMETERS_QUOTED="$(quote_params "$@")"
    if type "$FUNC" >/dev/null 2>&1; then
      gf_log_internal "$FUNC $PARAMETERS_QUOTED"
      eval "$FUNC $PARAMETERS_QUOTED"
    else
      gf_log_error "\`$COMMAND\` named \`${SUB_COMMAND}\` not found"
    fi
  else
    FORCE_INTERACTIVE=""
    if [ "$COMMAND" = 'interactive' ]; then
      COMMAND="$1"
      FORCE_INTERACTIVE="YES"
      shift
    fi

    PARAMETERS_QUOTED="$(quote_params "$@")"
    INTERACTIVE_FUNC="gf_${COMMAND}"
    NON_INTERACTIVE_FUNC="gf_${COMMAND}_direct"

    if [ -z "$FORCE_INTERACTIVE" ] && type "$NON_INTERACTIVE_FUNC" >/dev/null 2>&1; then
      gf_log_internal "$NON_INTERACTIVE_FUNC $PARAMETERS_QUOTED"
      eval "$NON_INTERACTIVE_FUNC $PARAMETERS_QUOTED"
    elif type "$INTERACTIVE_FUNC" >/dev/null 2>&1; then
      gf_log_internal "$INTERACTIVE_FUNC $PARAMETERS_QUOTED"
      eval "$INTERACTIVE_FUNC $PARAMETERS_QUOTED"
    else
      gf_log_error "\`$COMMAND\` not found"
    fi
  fi
}

git_fuzzy() {
  if [ "$#" = '0' ]; then
    gf_menu
  else
    gf_run "$@"
  fi
}

git_fuzzy "$@"
