#!/usr/bin/env bash
# Nexus CLI installer  —  curl -fsSL https://luisearch.pages.dev/install | bash
set -euo pipefail

BASE="https://luisearch.pages.dev"
DEST="${NEXUS_HOME:-$HOME/.nexus-cli}"
BIN="$HOME/.local/bin"

c()  { printf '\033[%sm%s\033[0m' "$1" "$2"; }
say() { printf '  %s\n' "$1"; }

printf '\n  %s\n\n' "$(c '1;35' '✦ Nexus CLI installer')"

# --- deps ---
if ! command -v python3 >/dev/null 2>&1; then
  say "$(c 31 '✗ python3 is required but not found.')"
  say "  Install it (e.g. 'sudo apt install python3') and re-run."
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  say "$(c 31 '✗ curl is required but not found.')"; exit 1
fi

# --- download into its own folder (from the update channel = single source of truth) ---
CLI_URL="${NEXUS_CLI_URL:-https://update.luisearch.pages.dev/nexus}"
say "$(c 2 'Downloading Nexus CLI…')"
mkdir -p "$DEST" "$BIN"
curl -fsSL "$CLI_URL" -o "$DEST/nexus_cli.py"
chmod +x "$DEST/nexus_cli.py"
ln -sf "$DEST/nexus_cli.py" "$BIN/nexus"
say "$(c 32 '✓') installed to $(c 36 "$DEST")"
say "$(c 32 '✓') linked $(c 36 "$BIN/nexus")"

# --- ensure ~/.local/bin is on PATH ---
add_path() {
  local rc="$1"
  [ -f "$rc" ] || return 0
  if ! grep -qs '.local/bin' "$rc"; then
    printf '\n# added by Nexus CLI installer\nexport PATH="$HOME/.local/bin:$PATH"\n' >> "$rc"
    say "$(c 32 '✓') added ~/.local/bin to PATH in $(c 36 "$rc")"
  fi
}
case ":$PATH:" in
  *":$BIN:"*) : ;;                       # already on PATH
  *)
    add_path "$HOME/.bashrc"
    add_path "$HOME/.zshrc"
    add_path "$HOME/.profile"
    NEEDS_RELOAD=1
    ;;
esac

# --- optional: qrencode for `nexus mobile` ---
if ! command -v qrencode >/dev/null 2>&1; then
  say "$(c 33 '•') optional: install $(c 1 qrencode) for QR sign-in ('nexus mobile')  —  sudo apt install qrencode"
fi

printf '\n  %s\n' "$(c '1;32' '✓ Done!')"
if [ "${NEEDS_RELOAD:-0}" = 1 ]; then
  say "Open a new terminal (or run: $(c 36 'export PATH=\"\$HOME/.local/bin:\$PATH\"')) then:"
else
  say "Get started:"
fi
say ""
say "  $(c 1 'nexus')                    show help"
say "  $(c 1 'nexus login <user>')       sign in with a password"
say "  $(c 1 'nexus mobile')             sign in by scanning a QR with your phone"
say "  $(c 1 'nexus watch')              live-tail all your chats"
say ""
say "More: $(c 36 "$BASE/cli")"
printf '\n'
