#!/usr/bin/env bash
set -euo pipefail

PACKAGE="${CLAVUE_PACKAGE:-clavue-v1}"
VERSION_INPUT="${1:-${CLAVUE_VERSION:-latest}}"

need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    printf 'Missing required command: %s\n' "$1" >&2
    exit 1
  fi
}

check_node() {
  need_cmd node

  local node_major node_minor
  node_major="$(node -p "process.versions.node.split('.')[0]")"
  node_minor="$(node -p "process.versions.node.split('.')[1]")"
  if [[ -z "$node_major" || "$node_major" -lt 22 ]] ||
    [[ "$node_major" -eq 22 && "$node_minor" -lt 18 ]]; then
    printf 'clavue-v1 requires Node.js 22.18 or newer. Found: %s\n' "$(node -v)" >&2
    exit 1
  fi
}

resolve_version() {
  if [[ "$VERSION_INPUT" != "latest" ]]; then
    printf '%s' "${VERSION_INPUT#v}"
    return 0
  fi

  npm view "$PACKAGE" version
}

main() {
  need_cmd npm
  check_node

  local version
  version="$(resolve_version)"
  if [[ -z "$version" ]]; then
    printf 'Unable to determine the latest %s version from npm.\n' "$PACKAGE" >&2
    exit 1
  fi

  printf 'Installing %s@%s globally from npm...\n' "$PACKAGE" "$version"
  printf 'For one-shot use without a global install, run: npx -y %s@%s\n' "$PACKAGE" "$version"
  npm install -g "${PACKAGE}@${version}"

  printf 'Installed %s@%s globally\n' "$PACKAGE" "$version"
  printf 'Available commands after npm install: clavue-v1\n'
  clavue-v1 --version || true

  printf '\nNext step:\n'
  printf '  Run: clavue-v1\n'
  printf '  First launch opens API setup. Choose "自定义 API 配置" to enter your API URL, key, and optional model slots.\n'
  printf '  You can reopen setup any time with: clavue-v1 provider\n'
}

main "$@"
