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

BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

die() {
  log_error "$1"
  exit 1
}

need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    die "Missing dependency: $1"
  fi
}

mktemp_dir() {
  mktemp -d 2>/dev/null || mktemp -d -t coolvibe
}

normalize_version() {
  local v="$1"
  if [ -z "$v" ] || [ "$v" = "latest" ]; then
    echo "latest"
    return 0
  fi
  # 移除 v 前缀（如有）
  case "$v" in
    v*) echo "${v#v}" ;;
    *) echo "$v" ;;
  esac
}

cdn_latest_tag() {
  curl -fsSL "https://get.coolvibe.io/latest.txt" | tr -d '[:space:]'
}

download_to() {
  local url="$1"
  local out="$2"

  if command -v curl >/dev/null 2>&1; then
    curl -fL --retry 3 --retry-delay 2 --connect-timeout 30 --max-time 300 -o "$out" "$url"
    return 0
  fi

  if command -v wget >/dev/null 2>&1; then
    wget --timeout=30 --tries=3 -O "$out" "$url"
    return 0
  fi

  die "Missing download tool: curl or wget"
}

show_help() {
  cat <<EOF
One-click install CoolVibe (download binary + setup background service)

Usage:
  $0

Environment variables (optional):
  COOLVIBE_VERSION   Default: latest (can specify 1.0.0)
  COOLVIBE_HOME      Default: ~/.coolvibe
EOF
}

main() {
  case "${1:-}" in
    "" ) ;;
    help|-h|--help) show_help; exit 0 ;;
    *) die "Unknown argument: $1 (use --help for usage)" ;;
  esac

  # Windows detection (uname returns versioned suffix like MINGW64_NT-10.0-19045)
  local os_name
  os_name="$(uname -s)"
  if [[ "$os_name" =~ ^(MINGW|MSYS|CYGWIN) ]]; then
    die "Windows detected: please use getcoolvibe.ps1"
  fi

  # Check for download tool (curl or wget)
  if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
    die "Missing download tool: curl or wget"
  fi
  need_cmd sed
  need_cmd grep

  local version
  version="$(normalize_version "${COOLVIBE_VERSION:-latest}")"
  if [ "$version" = "latest" ]; then
    log_info "Fetching latest version from get.coolvibe.io..."
    version="$(cdn_latest_tag)"
    [ -n "$version" ] || die "Failed to get latest version: check network or set COOLVIBE_VERSION"
  fi

  local tmp
  tmp="$(mktemp_dir)"
  local script_url="https://get.coolvibe.io/${version}/coolvibe.sh"
  local script_path="${tmp}/coolvibe.sh"

  log_info "Downloading management script: $script_url"
  download_to "$script_url" "$script_path"
  chmod +x "$script_path"

  log_info "Starting installation (COOLVIBE_HOME=${COOLVIBE_HOME:-$HOME/.coolvibe})..."
  COOLVIBE_VERSION="$version" COOLVIBE_HOME="${COOLVIBE_HOME:-$HOME/.coolvibe}" \
    bash "$script_path" install

  rm -rf "$tmp"
  log_success "Done."
}

main "$@"
