#!/usr/bin/env bash
set -euo pipefail

PYTHON_PACKAGE="${PYTHON_PACKAGE:-.[whisper]}"
VOXN_DATA_DIR="${VOXN_DATA_DIR:-$HOME/.local/share/voxn}"
USER_SYSTEMD_DIR="${USER_SYSTEMD_DIR:-$HOME/.config/systemd/user}"
USER_MAN_DIR="${USER_MAN_DIR:-$HOME/.local/share/man/man1}"
ASSUME_YES=0

for arg in "$@"; do
  case "$arg" in
    -y|--yes) ASSUME_YES=1 ;;
    --minimal) PYTHON_PACKAGE="." ;;
    -h|--help)
      printf 'usage: scripts/install-user [--yes] [--minimal]\n'
      exit 0
      ;;
    *) printf 'unknown option: %s\n' "$arg" >&2; exit 2 ;;
  esac
done

ask() {
  local prompt="$1"
  if (( ASSUME_YES )); then
    return 0
  fi
  read -r -p "$prompt [y/N] " reply
  [[ "$reply" == "y" || "$reply" == "Y" || "$reply" == "yes" || "$reply" == "YES" ]]
}

have() {
  command -v "$1" >/dev/null 2>&1
}

install_pacman_packages() {
  local packages=("$@")
  ((${#packages[@]})) || return 0
  if ! have pacman; then
    printf 'missing packages: %s\n' "${packages[*]}" >&2
    printf 'install them with your system package manager, then rerun this script.\n' >&2
    exit 1
  fi
  if ask "Install missing packages with pacman: ${packages[*]}?"; then
    sudo pacman -S --needed "${packages[@]}"
  else
    printf 'missing required packages: %s\n' "${packages[*]}" >&2
    exit 1
  fi
}

missing=()
have python3 || missing+=(python)
have uv || missing+=(uv)
have sox || missing+=(sox)
have fzf || missing+=(fzf)
have sqlite3 || missing+=(sqlite)
install_pacman_packages "${missing[@]}"

recommended=()
have wl-copy || recommended+=(wl-clipboard)
have notify-send || recommended+=(libnotify)
have pdftotext || recommended+=(poppler)
if ((${#recommended[@]})) && have pacman && ask "Install recommended packages: ${recommended[*]}?"; then
  sudo pacman -S --needed "${recommended[@]}"
fi

if ! have ollama; then
  if have pacman && ask "Install Ollama with pacman?"; then
    sudo pacman -S --needed ollama
  else
    printf 'ollama not found; local LLM formatting will not work until Ollama is installed.\n' >&2
  fi
fi

if have ollama; then
  if ! python3 - <<'PY' >/dev/null 2>&1
import urllib.request
urllib.request.urlopen("http://localhost:11434/api/tags", timeout=2)
PY
  then
    if ask "Ollama is installed but not reachable. Start and enable the system service?"; then
      sudo systemctl enable --now ollama
    fi
  fi
fi

uv tool install -e "$PYTHON_PACKAGE"
mkdir -p "$VOXN_DATA_DIR/wiki"
touch "$VOXN_DATA_DIR/voxns.md"
mkdir -p "$USER_MAN_DIR"
install -m 644 man/*.1 "$USER_MAN_DIR/"
mandb -q "$HOME/.local/share/man" 2>/dev/null || true
mkdir -p "$USER_SYSTEMD_DIR"
install -m 644 systemd/voxn-index.path "$USER_SYSTEMD_DIR/voxn-index.path"
install -m 644 systemd/voxn-index.service "$USER_SYSTEMD_DIR/voxn-index.service"
systemctl --user daemon-reload
systemctl --user enable --now voxn-index.path
voxn doctor
