#!/bin/sh
# Installs the Kainguru CLI on Linux or macOS (Windows: inside WSL 2):
#   curl -fsSL https://kainguru.com/install.sh | sh
# It needs Python 3.10 or newer. With pipx present it installs through pipx; otherwise it creates
# a private virtualenv in ~/.kainguru/venv and links the commands into ~/.local/bin. It never
# touches the system Python, and it never needs root.
set -eu

WHEEL="${KAINGURU_CLI_WHEEL:-https://kainguru.com/cli/kainguru_cli-0.1.0-py3-none-any.whl}"
HOME_DIR="${KAINGURU_HOME:-$HOME/.kainguru}"
BIN_DIR="$HOME/.local/bin"

say() { printf '%s\n' "$*"; }
fail() { printf 'install.sh: %s\n' "$*" >&2; exit 1; }

case "$(uname -s)" in
  Linux|Darwin) ;;
  *) fail "this installer runs on Linux and macOS; on Windows, run it inside WSL 2" ;;
esac

PY=""
for candidate in python3 python; do
  if command -v "$candidate" >/dev/null 2>&1 &&
     "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; then
    PY=$candidate
    break
  fi
done
[ -n "$PY" ] || fail "Python 3.10 or newer is needed (python3 was not found, or is older)"

if command -v pipx >/dev/null 2>&1; then
  say "Installing the Kainguru CLI with pipx..."
  pipx install --force "$WHEEL" >/dev/null
  pipx ensurepath >/dev/null 2>&1 || true
else
  say "Installing the Kainguru CLI into $HOME_DIR/venv..."
  "$PY" -m venv "$HOME_DIR/venv" ||
    fail "could not create a virtualenv (on Debian or Ubuntu: sudo apt install python3-venv, then run this again)"
  "$HOME_DIR/venv/bin/python" -m pip install --quiet --upgrade pip "$WHEEL" ||
    fail "pip could not install the CLI from $WHEEL"
  mkdir -p "$BIN_DIR"
  ln -sf "$HOME_DIR/venv/bin/kainguru" "$BIN_DIR/kainguru"
  ln -sf "$HOME_DIR/venv/bin/kg" "$BIN_DIR/kg"
fi

if command -v kainguru >/dev/null 2>&1; then
  say "Installed: $(command -v kainguru)"
else
  say "Installed into $BIN_DIR, which is not on your PATH yet. Add this line to your shell profile, then open a new terminal:"
  say "  export PATH=\"\$HOME/.local/bin:\$PATH\""
fi

command -v docker >/dev/null 2>&1 ||
  say "Note: Docker is needed for 'kainguru build' and 'kainguru test' (https://docs.docker.com/get-docker/). 'kainguru login' and 'push' work without it."

say ""
say "Next steps:"
say "  kainguru login        # paste an API key from app.kainguru.com -> Applications -> API keys"
say "  kainguru --help"
say "Guide: https://kainguru.com/docs"
