#!/usr/bin/env bash

_bashers_find_lib() {
  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
    local parent="$(dirname "$dir")"
    [[ "$parent" == "$dir" ]] && break
    dir="$parent"
  done
  return 1
}

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

setup() {
  local want_frozen=0 want_no_cache=0 dry_run=0 rm_venv=0

  for arg in "$@"; do
    case "$arg" in
      -h|--help)
        _bashers_color_init
        _bashers_print_title "setup"
        _bashers_print_usage "setup [--rm] [--frozen|--locked|--sync] [--dry-run]"
        _bashers_print_section "Description"
        _bashers_print_bullet "Install project dependencies using uv or poetry."
        _bashers_print_section "Options"
        _bashers_print_kv "--rm" "Remove .venv before install (implies --no-cache)"
        _bashers_print_kv "--frozen" "Use a locked/frozen install if supported"
        _bashers_print_kv "--locked" "Same as --frozen"
        _bashers_print_kv "--sync" "Same as --frozen"
        _bashers_print_kv "--dry-run" "Print the commands without executing"
        return 0
        ;;
      --dry-run)
        dry_run=1
        ;;
      --rm)
        rm_venv=1
        want_no_cache=1
        ;;
      --frozen|--locked|--sync)
        want_frozen=1
        ;;
      --*)
        echo "[setup]: usage: setup [--rm] [--frozen|--locked|--sync] [--dry-run]" >&2
        return 2
        ;;
      *)
        echo "[setup]: usage: setup [--rm] [--frozen|--locked|--sync] [--dry-run]" >&2
        return 2
        ;;
    esac
  done

  if (( rm_venv )); then
    if (( dry_run )); then
      echo "rm -rf .venv"
    else
      rm -rf .venv
    fi
  fi

  _need() { command -v "$1" >/dev/null 2>&1 || { echo "[setup]: $2" >&2; return 127; }; }
  _has()  { [[ -f "$1" ]] || return 1; }
  _tbl()  { [[ -f pyproject.toml ]] && grep -Eq "^\[$1\]" pyproject.toml; }

  if _has uv.lock || _tbl project; then
    _need uv "uv required but not on PATH" || return $?
    local uv_opts="--all-extras"
    (( want_frozen )) && uv_opts="$uv_opts --frozen"
    (( want_no_cache )) && uv_opts="$uv_opts --no-cache"
    if (( dry_run )); then
      echo "uv sync $uv_opts"
      return 0
    fi
    uv sync $uv_opts
    return $?
  fi

  if _has poetry.lock || _tbl tool.poetry; then
    _need poetry "poetry required but not on PATH" || return $?
    local poetry_opts="--all-extras"
    (( want_frozen )) && poetry_opts="$poetry_opts --sync"
    (( want_no_cache )) && poetry_opts="$poetry_opts --no-cache"
    if (( dry_run )); then
      echo "poetry install $poetry_opts"
      return 0
    fi
    poetry install $poetry_opts
    return $?
  fi

  echo "[setup]: no uv/poetry lockfile and no pyproject.toml with [project]/[tool.poetry] in $(pwd)" >&2
  return 2
}
