#!/bin/sh
# kelam.sh — one-command installer for the Kelam CLI.
#
#   curl -fsSL https://kelam.sh | sh
#
# Installs the `kelam` command (a thin, dependency-light client for the Kelam voice-agent
# platform) from PyPI, using the best available Python installer: uv > pipx > pip --user.
# Then prints how to point the CLI at a server and authenticate.
#
# Environment overrides:
#   KELAM_PKG       package name to install      (default: kelam)
#   KELAM_API_URL   server the CLI talks to        (printed as a setup hint if set)
#   KELAM_INSTALLER force one of: uv | pipx | pip   (default: auto-detect)
set -eu

KELAM_PKG="${KELAM_PKG:-kelam}"

RED=''; GRN=''; YEL=''; BLD=''; RST=''
if [ -t 1 ]; then RED='\033[31m'; GRN='\033[32m'; YEL='\033[33m'; BLD='\033[1m'; RST='\033[0m'; fi
say()  { printf "%b\n" "$*"; }
info() { say "${BLD}kelam${RST} $*"; }
warn() { say "${YEL}warning:${RST} $*" >&2; }
die()  { say "${RED}error:${RST} $*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

info "installing the Kelam CLI ($KELAM_PKG) from PyPI…"

installer="${KELAM_INSTALLER:-}"
if [ -z "$installer" ]; then
  if have uv;     then installer=uv
  elif have pipx; then installer=pipx
  elif have python3 || have python; then installer=pip
  else
    info "no uv/pipx/pip found — bootstrapping uv…"
    curl -fsSL https://astral.sh/uv/install.sh | sh
    export PATH="$HOME/.local/bin:$PATH"
    have uv || die "uv bootstrap failed; install Python 3.11+ and re-run"
    installer=uv
  fi
fi

case "$installer" in
  uv)   info "using uv tool install"; uv tool install --upgrade "$KELAM_PKG" ;;
  pipx) info "using pipx";            pipx install --force "$KELAM_PKG" ;;
  pip)  PY=python3; have python3 || PY=python
        info "using $PY -m pip install --user"
        "$PY" -m pip install --user --upgrade "$KELAM_PKG" ;;
  *)    die "unknown installer: $installer" ;;
esac

if ! have kelam; then
  warn "'kelam' isn't on your PATH yet."
  case "$installer" in
    uv)  warn "run: uv tool update-shell   (then restart your shell)" ;;
    pip) warn "add your user bin to PATH, e.g.  export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
  esac
fi

say ""
info "${GRN}installed.${RST}"
say ""
say "Next steps:"
say "  1) Point the CLI at your server:"
if [ -n "${KELAM_API_URL:-}" ]; then
  say "       export KELAM_API_URL=${KELAM_API_URL}"
else
  say "       export KELAM_API_URL=https://<your-kelam-host>"
fi
say "  2) If the server requires a password (KELAM_API_PASSWORD set there):"
say "       export KELAM_PASSWORD=<the shared password>"
say "  3) Try it:"
say "       kelam list"
say ""
say "Tip: add the two exports to your ~/.zshrc or ~/.bashrc so they persist."
