#!/usr/bin/env bash
# Installer for ai-eidechse-cli, served via a domain.
#
# Usage (on the remote machine):
#   curl -fsSL https://eidechse.nnsn.pro/install.sh | bash
#
# What it does:
#   1) requires ONE of uv or pipx to be available — installs nothing itself,
#      only tells you how to put it if both are missing
#   2) reads the latest version from <base>/latest/VERSION
#   3) if the same version is already installed — does nothing
#   4) installs/updates the wheel from <base>/latest/ via uv or pipx
#
# Installs ONLY the built wheel — no repo, no source tree on the machine.
set -euo pipefail

BASE_URL="https://eidechse.nnsn.pro"
PKG="ai-eidechse-cli"
CMD="eidechse"

log()  { printf '%s\n' "$*"; }
err()  { printf 'error: %s\n' "$*" >&2; }

# 1) manager: uv or pipx (no bootstrap) ---------------------------------
pick_manager() {
  if command -v uv >/dev/null 2>&1; then
    echo uv
  elif command -v pipx >/dev/null 2>&1; then
    echo pipx
  else
    err "ONE of uv or pipx is required on this machine, and neither is present."
    err "install one of them and run again:"
    err "  uv   → https://docs.astral.sh/uv/getting-started/installation/"
    err "  pipx → https://pipx.pypa.io/stable/installation/"
    exit 1
  fi
}

# 2) latest version from the domain -------------------------------------
remote_version() {
  curl -fsSL "${BASE_URL}/latest/VERSION" | tr -d '[:space:]'
}

# the installed version (empty if missing) ------------------------------
local_version() {
  command -v "${CMD}" >/dev/null 2>&1 || return 0
  "${CMD}" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1 || true
}

main() {
  local mgr remote local wheel_url
  mgr="$(pick_manager)"

  remote="$(remote_version)"
  if [[ -z "${remote}" ]]; then
    err "cannot read ${BASE_URL}/latest/VERSION"
    exit 1
  fi

  local="$(local_version)"
  if [[ -n "${local}" && "${local}" == "${remote}" ]]; then
    log "✓ already latest (${local}) — nothing to do."
    exit 0
  fi

  wheel_url="${BASE_URL}/latest/ai_eidechse_cli-${remote}-py3-none-any.whl"
  log "installing ${PKG} ${remote} via ${mgr}…"

  case "${mgr}" in
    uv)   uv tool install --force "${PKG} @ ${wheel_url}" ;;
    pipx) pipx install --force "${wheel_url}" ;;
  esac

  log "✓ done. Check with: ${CMD} --version"
  log "Then add a config: ~/.ai-eidechse-cli/config.json (see SETUP.md)."
}

main "$@"
