#!/bin/sh
# Spix CLI Installer
# Usage: curl -sf https://spix.sh/install | sh
#
# Supports: macOS (arm64, x86_64), Linux (x86_64, arm64)
# For Windows: use `irm https://spix.sh/install.ps1 | iex` in PowerShell

set -e

REPO="Spix-HQ/spix-cli"
INSTALL_DIR="/usr/local/bin"
BINARY_NAME="spix"

# Colors (if terminal supports them)
RED='\033[0;31m'
GREEN='\033[0;32m'
DIM='\033[2m'
RESET='\033[0m'

info() {
  printf "${DIM}%s${RESET}\n" "$1"
}

success() {
  printf "${GREEN}✓ %s${RESET}\n" "$1"
}

error() {
  printf "${RED}✗ %s${RESET}\n" "$1" >&2
  exit 1
}

# Detect OS
detect_os() {
  case "$(uname -s)" in
    Darwin) echo "darwin" ;;
    Linux)  echo "linux" ;;
    MINGW*|MSYS*|CYGWIN*)
      error "Windows detected. Use PowerShell instead: irm https://spix.sh/install.ps1 | iex"
      ;;
    *) error "Unsupported operating system: $(uname -s)" ;;
  esac
}

# Detect architecture (matches release asset naming)
detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)  echo "x64" ;;
    arm64|aarch64) echo "arm64" ;;
    *) error "Unsupported architecture: $(uname -m)" ;;
  esac
}

# Get latest release version from GitHub API
get_latest_version() {
  if command -v curl >/dev/null 2>&1; then
    curl -sf "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/'
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/'
  else
    error "Neither curl nor wget found. Please install one and try again."
  fi
}

# Download file
download() {
  local url="$1"
  local dest="$2"

  if command -v curl >/dev/null 2>&1; then
    curl -sfL "$url" -o "$dest"
  elif command -v wget >/dev/null 2>&1; then
    wget -q "$url" -O "$dest"
  fi
}

main() {
  local os arch version asset_name url tmpdir

  os="$(detect_os)"
  arch="$(detect_arch)"
  version="$(get_latest_version)"

  if [ -z "$version" ]; then
    error "Could not determine latest version. Check your network connection."
  fi

  asset_name="spix-${os}-${arch}"
  info "Downloading ${asset_name} ${version}..."

  url="https://github.com/${REPO}/releases/download/${version}/${asset_name}"
  tmpdir="$(mktemp -d)"
  trap 'rm -rf "$tmpdir"' EXIT

  download "$url" "$tmpdir/${BINARY_NAME}" || error "Download failed. URL: $url"

  info "Installing to ${INSTALL_DIR}..."

  chmod +x "$tmpdir/${BINARY_NAME}"

  # Install binary (try without sudo first, fall back to sudo)
  if [ -w "$INSTALL_DIR" ]; then
    mv "$tmpdir/${BINARY_NAME}" "$INSTALL_DIR/${BINARY_NAME}"
  else
    info "Requesting sudo access to install to ${INSTALL_DIR}..."
    sudo mv "$tmpdir/${BINARY_NAME}" "$INSTALL_DIR/${BINARY_NAME}"
  fi

  success "Spix ${version} installed to ${INSTALL_DIR}/${BINARY_NAME}"

  # Track install (non-blocking, silent, best-effort)
  curl -sf -X POST "https://api.spix.sh/v1/track/install/" \
    -H "Content-Type: application/json" \
    -d "{\"os\":\"${os}\",\"arch\":\"${arch}\",\"version\":\"${version}\"}" \
    >/dev/null 2>&1 &

  echo ""
  info "Get started:"
  echo "  spix auth login"
  echo "  spix --help"
}

main
