#!/usr/bin/env bash

_bashers_python() {
  local candidate
  candidate="$(dirname "$0")/python"
  if [[ -x "$candidate" ]]; then
    echo "$candidate"
    return 0
  fi
  command -v python3 2>/dev/null || command -v python 2>/dev/null
}

_bashers_version() {
  local python_bin="$(_bashers_python)"
  if [[ -z "$python_bin" ]]; then
    echo "unknown"
    return 0
  fi
  "$python_bin" - <<'PY'
import importlib.metadata as metadata
try:
    print(metadata.version("bashers"))
except metadata.PackageNotFoundError:
    print("unknown")
PY
}

_bashers_find_lib() {
  local pkg_dir=""
  local python_bin="$(_bashers_python)"
  if [[ -n "$python_bin" ]]; then
    pkg_dir="$(
      "$python_bin" - <<'PY'
import importlib.resources as resources
print(resources.files("bashers"))
PY
    )"
    if [[ -n "$pkg_dir" && -f "$pkg_dir/_bashers_lib" ]]; then
      echo "$pkg_dir/_bashers_lib"
      return 0
    fi
  fi

  local dir
  dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  while [[ "$dir" != "/" ]]; do
    if [[ -f "$dir/_bashers_lib" ]]; then
      echo "$dir/_bashers_lib"
      return 0
    fi
    dir="$(dirname "$dir")"
  done
  return 1
}

_bashers_lib="$(_bashers_find_lib)"
[[ -n "$_bashers_lib" ]] && source "$_bashers_lib"

print_help() {
  local pkg_dir="$1"
  _bashers_color_init
  _bashers_print_title "Bashers - Bash command helpers"
  echo ""
  _bashers_print_usage "bashers <COMMAND> [ARGS]"
  echo ""
  _bashers_print_section "Commands"
  _bashers_print_kv "help" "Display help for bashers or a command"
  if [[ -d "$pkg_dir" ]]; then
    declare -A descriptions=(
      [setup]="Install project dependencies (uv/poetry)"
      [show]="List installed packages (uv/poetry)"
      [update]="Update dependencies (uv/poetry)"
    )
    mapfile -t commands < <(find "$pkg_dir" -type f \
      | sed "s|^$pkg_dir/||" \
      | grep -vE '(^__|/__)' \
      | grep -vE '(^\.|/\.)' \
      | grep -vE '(^_|/_)' \
      | grep -vE '^bashers$' \
      | grep -vE '\.(py|pyc)$' \
      | xargs -n1 basename \
      | sort -u)
    for cmd in "${commands[@]}"; do
      if [[ -n "${descriptions[$cmd]-}" ]]; then
        _bashers_print_kv "$cmd" "${descriptions[$cmd]}"
      else
        printf "  %s%s%s\n" "$BASHERS_CYAN" "$cmd" "$BASHERS_RESET"
      fi
    done
  fi
  echo ""
  echo "Use ${BASHERS_BOLD}bashers <command> --help${BASHERS_RESET} for more details."
}

_bashers_is_visible() {
  local rel="$1"
  [[ -z "$rel" ]] && return 1
  [[ "$rel" == __* || "$rel" == .* || "$rel" == _* ]] && return 1
  [[ "$rel" == */__* || "$rel" == */.* || "$rel" == */_* ]] && return 1
  [[ "$rel" == *.py || "$rel" == *.pyc ]] && return 1
  return 0
}

if [[ $# -eq 0 ]]; then
  python_bin="$(_bashers_python)"
  pkg_dir=""
  if [[ -n "$python_bin" ]]; then
    pkg_dir="$(
      "$python_bin" - <<'PY'
import importlib.resources as resources
print(resources.files("bashers"))
PY
    )"
  fi
  print_help "$pkg_dir"
  exit 0
fi

command="$1"
shift

case "$command" in
  help|-h|--help)
    python_bin="$(_bashers_python)"
    pkg_dir=""
    if [[ -n "$python_bin" ]]; then
      pkg_dir="$(
        "$python_bin" - <<'PY'
import importlib.resources as resources
print(resources.files("bashers"))
PY
      )"
    fi
    print_help "$pkg_dir"
    exit 0
    ;;
  --version|-V)
    echo "bashers $(_bashers_version)"
    exit 0
    ;;
esac

python_bin="$(_bashers_python)"
pkg_dir=""
if [[ -n "$python_bin" ]]; then
  pkg_dir="$(
    "$python_bin" - <<'PY'
import importlib.resources as resources
print(resources.files("bashers"))
PY
  )"
fi

if [[ -z "$pkg_dir" || ! -d "$pkg_dir" ]]; then
  echo "bashers: unable to locate package data (missing bashers install?)" >&2
  exit 127
fi

script_path=""
if [[ "$command" == */* ]]; then
  candidate="$pkg_dir/$command"
  [[ -f "$candidate" ]] && script_path="$candidate"
else
  matches=()
  while IFS= read -r candidate; do
    rel="${candidate#"$pkg_dir"/}"
    _bashers_is_visible "$rel" || continue
    matches+=("$candidate")
  done < <(find "$pkg_dir" -type f -name "$command")
  if [[ ${#matches[@]} -gt 1 ]]; then
    echo "Command '$command' is ambiguous. Use a path:" >&2
    for match in "${matches[@]}"; do
      echo "  ${match#"$pkg_dir"/}" >&2
    done
    exit 2
  fi
  [[ ${#matches[@]} -eq 1 ]] && script_path="${matches[0]}"
fi

if [[ -n "$script_path" && -f "$script_path" ]]; then
  script_name="$(basename "$script_path")"
  _bashers_color_init
  if grep -qE "^[[:space:]]*${script_name}[[:space:]]*\\(\\)[[:space:]]*\\{" "$script_path"; then
    _bashers_run bash -c "source \"$script_path\" && $script_name \"\$@\"" -- "$@"
    exit $?
  fi
  _bashers_run "$script_path" "$@"
  exit $?
fi

echo "Command '$command' not found. Use 'bashers help' for available commands."
exit 1
