#!/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): Homebrew tap > uv > pipx > (bootstrap uv). Bare `pip install --user` is never
# auto-picked — PEP 668 externally-managed Pythons (Debian 12+, Ubuntu 23.04+, Homebrew)
# reject it, so a stock python3 would fail mid-install; uv works everywhere. Then prints
# how to point the CLI at a server and authenticate.
#
# Re-running is safe: once `kelam` is on PATH this script says so and exits 0 instead of
# reinstalling. (AI agents re-run installers in a loop when a command looks missing — the
# guard breaks that loop.) Upgrades go through `kelam update`, not through this script.
#
# 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: brew | uv | pipx | pip   (default: auto-detect; pip is
#                   explicit-only and requires a Python that allows `pip install --user`)
#   KELAM_REINSTALL set to 1 to reinstall even when kelam is already on PATH
set -eu

KELAM_PKG="${KELAM_PKG:-kelam}"
BREW_FORMULA="nousdata/tap/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; }

# Already installed? Then this run has nothing to do — report and exit 0, don't
# reinstall. (`kelam --version` exists from CLI 0.4.0; older installs skip the version.)
if [ -z "${KELAM_REINSTALL:-}" ] && have kelam; then
  ver="$(kelam --version 2>/dev/null || true)"
  info "already installed${ver:+ — ${ver}} at $(command -v kelam); nothing to do."
  say "  upgrade:    kelam update    (older CLIs: uv tool upgrade kelam / pipx upgrade kelam / brew upgrade kelam)"
  say "  reinstall:  KELAM_REINSTALL=1  curl -fsSL https://kelam.sh | sh"
  exit 0
fi

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

installer="${KELAM_INSTALLER:-}"
if [ -z "$installer" ]; then
  # Homebrew first when present: brew's bin dir is on PATH for every shell (including
  # agents' non-interactive subshells), so the install needs zero PATH surgery. Only
  # auto-picked for the real package — the tap formula is pinned to `kelam`.
  if [ "$KELAM_PKG" = kelam ] && have brew; then installer=brew
  elif have uv;   then installer=uv
  elif have pipx; then installer=pipx
  else
    info "no brew/uv/pipx 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 uv or pipx and re-run (or force KELAM_INSTALLER=pip if your Python permits pip --user)"
    installer=uv
  fi
fi

case "$installer" in
  brew) info "using Homebrew ($BREW_FORMULA)"; brew install "$BREW_FORMULA" ;;
  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
  case "$installer" in
    uv)
      # Persist for future shells, and export for THIS process — so the verification
      # below sees it and the very next command can be `kelam ...`.
      uv tool update-shell >/dev/null 2>&1 || true
      BINDIR="$(uv tool dir --bin 2>/dev/null || printf '%s' "$HOME/.local/bin")"
      export PATH="$BINDIR:$PATH" ;;
    pipx)
      pipx ensurepath >/dev/null 2>&1 || true
      export PATH="$HOME/.local/bin:$PATH" ;;
    pip)
      export PATH="$HOME/.local/bin:$PATH" ;;
  esac
fi

say ""
if have kelam; then
  ver="$(kelam --version 2>/dev/null || true)"
  info "${GRN}installed${RST}${ver:+ — ${ver}} at $(command -v kelam)"
  case "$installer" in
    uv|pipx|pip)
      say "  Future shells find it automatically (shell config updated). For THIS shell, run:"
      say "    export PATH=\"$(dirname "$(command -v kelam)"):\$PATH\"" ;;
  esac
else
  warn "'kelam' isn't on your PATH yet — restart your shell, or add \$HOME/.local/bin to PATH."
fi

say ""
say "Next steps:"
say "  1) Sign in — opens your browser (Google or GitHub), gives you your own"
say "     workspace, and saves the credential locally so you need no env vars after:"
say "       kelam login"
say "  2) Then try it (the CLI talks to the public Kelam server by default):"
say "       kelam status          # where your workspace stands, in one round"
say "       kelam create my-bot   # scaffold an agent — a phone number attaches automatically"
if [ -n "${KELAM_API_URL:-}" ]; then
  say "  3) Using your own server instead of the public one (default: https://api.kelam.sh)?"
  say "       export KELAM_API_URL=${KELAM_API_URL}"
else
  say "  3) Using your own server instead of the public one (default: https://api.kelam.sh)?"
  say "       export KELAM_API_URL=http://<your-kelam-host>:8000"
fi
say "     Self-hosted with shared-password auth (KELAM_API_PASSWORD set on the server)?"
say "       kelam login --env-var KELAM_PASSWORD   # reads it from the env, never off argv"
say "       #   or, ad hoc:  export KELAM_PASSWORD=<the shared password>"
say "  4) Upgrade later with:  kelam update"
say ""
say "Tip: add any exports to your ~/.zshrc or ~/.bashrc so they persist."
