#!/usr/bin/env bash
# Copyright 2026 Alibaba Group / UMeng
# Licensed under the MIT License
#
# Installer for umeng-cli (UMeng CLI).
# Downloads the pre-built binary from UMeng OSS.
# No Rust, Node.js, or other dependencies required.
#
# Usage:
#   curl -fsSL https://um-community.oss-cn-zhangjiakou.aliyuncs.com/umeng-cli/install.sh | sh
#   curl -fsSL https://um-community.oss-cn-zhangjiakou.aliyuncs.com/umeng-cli/install.sh | sh -s -- 0.2.14
#   curl -fsSL .../install.sh | sh -s -- -v 0.2.14 -d ~/.local/bin
#   curl -fsSL .../install.sh | sh -s -- --version 0.2.14 --skip-path --no-skills
#
# Options:
#   -h, --help          Display this help and exit
#   -v, --version       Version to install (default: latest)
#   -d, --install-dir   Directory to install the binary
#   --skip-path         Skip prepending install dir to PATH and skip appending to shell rc
#   --no-skills         Skip installing skills after binary installation
#   -f, --force         Force re-download even if the same version is already installed
#
# Environment variables (all optional):
#   UMENG_BASE_URL      -- base URL for downloads (default: https://um-community.oss-cn-zhangjiakou.aliyuncs.com/umeng-cli)
#   UMENG_INSTALL_DIR   -- where to put the binary
#   UMENG_VERSION       -- version to install
#   UMENG_INSTALL_NAME  -- custom binary name (default: umeng-cli)
#   UMENG_SKIP_PATH     -- set to 1 to skip PATH setup
#   UMENG_NO_SKILLS     -- set to 1 to skip skills installation

set -euo pipefail

BIN_NAME="umeng-cli"
OSS_BASE_URL="${UMENG_BASE_URL:-https://um-community.oss-cn-zhangjiakou.aliyuncs.com/umeng-cli}"
VERSIONS_FILE="versions.json"

VERSION="latest"
INSTALL_DIR=""
INSTALL_NAME="${UMENG_INSTALL_NAME:-$BIN_NAME}"
SKIP_PATH="${UMENG_SKIP_PATH:-0}"
NO_SKILLS="${UMENG_NO_SKILLS:-0}"
FORCE="${UMENG_FORCE_INSTALL:-0}"

# ── Color output ─────────────────────────────────────────────────────────

if [ -t 1 ]; then
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[1;33m'
  BLUE='\033[0;34m'
  NC='\033[0m'
else
  RED=''
  GREEN=''
  YELLOW=''
  BLUE=''
  NC=''
fi

info() { printf "${BLUE}Info:${NC} %s\n" "$*"; }
success() { printf "${GREEN}Success:${NC} %s\n" "$*"; }
warn() { printf "${YELLOW}Warning:${NC} %s\n" "$*"; }
error() { printf "${RED}Error:${NC} %s\n" "$*" >&2; exit 1; }

# ── HOME fallback ────────────────────────────────────────────────────────

if [ -z "${HOME:-}" ] || [ "$HOME" = "/" ]; then
  HOME="$(getent passwd "$(id -u)" 2>/dev/null | cut -d: -f6)" || true
  [ -z "$HOME" ] || [ "$HOME" = "/" ] && HOME="/root"
  warn "\$HOME is not set or invalid, defaulting to $HOME"
fi

# ── Help ─────────────────────────────────────────────────────────────────

show_help() {
  cat << EOF

      umeng-cli Installer

Usage:
  curl -fsSL ${OSS_BASE_URL}/install.sh | sh
  curl -fsSL ${OSS_BASE_URL}/install.sh | sh -s -- 0.2.14
  curl -fsSL ${OSS_BASE_URL}/install.sh | sh -s -- -v 0.2.14 -d ~/.local/bin

Options:
  -h, --help          Display this help and exit
  -v, --version       Version to install (default: latest)
  -d, --install-dir   Directory to install the binary
  --skip-path         Skip prepending install dir to PATH and skip appending to shell rc
  --no-skills         Skip installing skills after binary installation

Environment variables (all optional):
  UMENG_BASE_URL      -- base URL for downloads
  UMENG_INSTALL_DIR   -- where to put the binary
  UMENG_VERSION       -- version to install
  UMENG_INSTALL_NAME  -- custom binary name (default: umeng-cli)
  UMENG_SKIP_PATH     -- set to 1 to skip PATH setup
  UMENG_NO_SKILLS     -- set to 1 to skip skills installation

EOF
}

# ── Args parsing ─────────────────────────────────────────────────────────

set_version() {
  if [ -z "$1" ]; then
    error "--version requires a value"
  fi
  VERSION="$1"
}

normalize_version() {
  case "$VERSION" in
    latest) return 0 ;;
    v*) VERSION="${VERSION#v}" ;;
  esac

  if ! printf '%s\n' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
    error "Invalid version: $VERSION (expected latest or a semantic version such as 0.2.14)"
  fi
}

parse_args() {
  while [ $# -gt 0 ]; do
    case "$1" in
      -h|--help)
        show_help
        exit 0
        ;;
      -v|--version)
        if [ $# -lt 2 ]; then error "--version requires a value"; fi
        set_version "$2"
        shift
        ;;
      --version=*)
        set_version "${1#--version=}"
        ;;
      -d|--install-dir)
        if [ $# -lt 2 ]; then error "--install-dir requires a value"; fi
        INSTALL_DIR="$2"
        shift
        ;;
      --install-dir=*)
        INSTALL_DIR="${1#--install-dir=}"
        ;;
      --skip-path)
        SKIP_PATH=1
        ;;
      --no-skills)
        NO_SKILLS=1
        ;;
      -f|--force)
        FORCE=1
        ;;
      --)
        shift
        break
        ;;
      -*)
        error "Unknown option: $1 (try --help)"
        ;;
      *)
        set_version "$1"
        ;;
    esac
    shift
  done

  normalize_version
}

# ── CWD guard ────────────────────────────────────────────────────────────

guard_cwd() {
  local cwd_abs guard_home cwd_real home_real
  cwd_abs="$(pwd 2>/dev/null || echo "$PWD")"
  guard_home="$HOME"
  cwd_real="$(cd "$cwd_abs" 2>/dev/null && pwd -P)" || cwd_real="$cwd_abs"
  home_real="$(cd "$guard_home" 2>/dev/null && pwd -P)" || home_real="$guard_home"

  case "$cwd_real" in
    "$home_real/.claude"|"$home_real/.claude/"*)
      warn "Current directory ($cwd_real) is inside the Claude config directory."
      warn "To avoid accidental cleanup, run the installer from a different directory:"
      warn "  cd /tmp && curl -fsSL ${OSS_BASE_URL}/install.sh | sh"
      ;;
  esac
}

# ── Helpers ──────────────────────────────────────────────────────────────

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

download() {
  local url="$1" dest="$2"
  if need_cmd curl; then
    curl -fsSL "$url" -o "$dest"
  elif need_cmd wget; then
    wget -qO "$dest" "$url"
  else
    error "curl or wget is required but neither was found"
  fi
}

download_soft() {
  local url="$1" dest="$2"
  if need_cmd curl; then
    curl -fsSL "$url" -o "$dest"
    return $?
  fi
  if need_cmd wget; then
    wget -qO "$dest" "$url"
    return $?
  fi
  return 1
}

detect_platform() {
  local os arch
  os="$(uname -s)"
  arch="$(uname -m)"

  case "$os" in
    Darwin*) os="darwin" ;;
    Linux*)  os="linux" ;;
    *) error "Unsupported OS: $os. Windows users please use install.ps1." ;;
  esac

  case "$arch" in
    x86_64|amd64) arch="amd64" ;;
    arm64|aarch64) arch="arm64" ;;
    *) error "Unsupported architecture: $arch" ;;
  esac

  echo "${os}-${arch}"
}

resolve_install_dir() {
  if [ -n "$INSTALL_DIR" ]; then
    printf '%s\n' "$INSTALL_DIR"
    return 0
  fi

  if [ -n "${UMENG_INSTALL_DIR:-}" ]; then
    printf '%s\n' "$UMENG_INSTALL_DIR"
    return 0
  fi

  case "$(uname -s)" in
    Darwin*)
      if [ -d "/usr/local/bin" ] && [ -w "/usr/local/bin" ]; then
        printf '%s\n' "/usr/local/bin"
      else
        printf '%s\n' "$HOME/.local/bin"
      fi
      ;;
    *)
      printf '%s\n' "$HOME/.local/bin"
      ;;
  esac
}

# ── JSON parsing (Python preferred, shell fallback) ──────────────────────

parse_json_field() {
  local json_file="$1" field="$2"
  grep "\"$field\"" "$json_file" | sed 's/.*"'$field'":[[:space:]]*"\([^"]*\)".*/\1/' | head -1
}

parse_platform_field() {
  local json_file="$1" platform="$2" field="$3"
  # Extract the platform block and then the field
  awk -v platform="\"$platform\":" -v field="\"$field\"" '
    $0 ~ platform { in_block=1 }
    in_block && $0 ~ field {
      match($0, /"[^"]*":[[:space:]]*"([^"]*)/, arr)
      if (length(arr) > 1) { print arr[1]; exit }
    }
    in_block && /\}/ { in_block=0 }
  ' "$json_file" | head -1
}

resolve_download_info() {
  local json_file="$1" platform="$2" target_version="$3"
  local url checksum

  if need_cmd python3; then
    url="$(python3 -c "
import json
with open('$json_file') as f: data = json.load(f)
print(data['versions']['$target_version']['platforms']['$platform']['url'])
" 2>/dev/null)" || url=""
    checksum="$(python3 -c "
import json
with open('$json_file') as f: data = json.load(f)
print(data['versions']['$target_version']['platforms']['$platform']['checksum'].replace('sha256:', ''))
" 2>/dev/null)" || checksum=""
  elif need_cmd python; then
    url="$(python -c "
import json
with open('$json_file') as f: data = json.load(f)
print(data['versions']['$target_version']['platforms']['$platform']['url'])
" 2>/dev/null)" || url=""
    checksum="$(python -c "
import json
with open('$json_file') as f: data = json.load(f)
print(data['versions']['$target_version']['platforms']['$platform']['checksum'].replace('sha256:', ''))
" 2>/dev/null)" || checksum=""
  fi

  if [ -z "$url" ]; then
    url="$(parse_platform_field "$json_file" "$platform" "url")"
  fi
  if [ -z "$checksum" ]; then
    checksum="$(parse_platform_field "$json_file" "$platform" "checksum" | sed 's/^sha256://')"
  fi

  printf '%s\n' "$url"
  printf '%s\n' "$checksum"
}

# ── Version comparison ───────────────────────────────────────────────────

compare_versions() {
  local v1="$1" v2="$2"
  if [ "$v1" = "$v2" ]; then
    return 0
  fi

  local p1 p2
  for i in 1 2 3; do
    p1="$(echo "$v1" | tr '.' ' ' | cut -d' ' -f$i)"
    p2="$(echo "$v2" | tr '.' ' ' | cut -d' ' -f$i)"
    [ -z "$p1" ] && p1=0
    [ -z "$p2" ] && p2=0

    if [ "$p1" -gt "$p2" ]; then
      return 1
    elif [ "$p1" -lt "$p2" ]; then
      return 2
    fi
  done

  return 0
}

# ── Check installed version ──────────────────────────────────────────────

check_installed_version() {
  local install_target="$1" target_version="$2"
  local current_version=""

  if [ -x "$install_target" ]; then
    # umeng-cli --version 输出格式：umeng-cli 0.2.14 (shell: <path>)
    # 使用正则提取 semver 版本号，避免输出格式变化导致解析错误
    current_version="$("$install_target" --version 2>/dev/null | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)" || true
  fi

  if [ -z "$current_version" ]; then
    return 1
  fi

  info "Current installed version at $install_target: $current_version"

  case "$current_version" in
    *[!0-9.]*)
      warn "Non-release version detected ($current_version), proceeding with install"
      return 1
      ;;
  esac

  local vc=0
  compare_versions "$current_version" "$target_version" || vc=$?

  case $vc in
    0)
      info "umeng-cli $target_version is already installed"
      return 0
      ;;
    1)
      warn "Installed version $current_version is newer than target $target_version"
      return 0
      ;;
    *)
      info "Newer version $target_version is available (currently $current_version)"
      return 1
      ;;
  esac
}

# ── Checksum verification ────────────────────────────────────────────────

verify_checksum() {
  local file="$1" expected="$2"
  local actual=""

  if [ -z "$expected" ]; then
    warn "No checksum provided, skipping verification"
    return 0
  fi

  if need_cmd sha256sum; then
    actual="$(sha256sum "$file" | cut -d' ' -f1)"
  elif need_cmd shasum; then
    actual="$(shasum -a 256 "$file" | cut -d' ' -f1)"
  else
    warn "SHA256 tool not found, skipping verification"
    return 0
  fi

  if [ "$actual" != "$expected" ]; then
    error "Checksum verification failed. Expected: $expected, Got: $actual"
  fi

  success "Checksum verified successfully"
}

# ── PATH setup ───────────────────────────────────────────────────────────

ensure_install_dir_in_path() {
  local dir="$1"
  if [ "$SKIP_PATH" = "1" ]; then
    info "Skipping PATH setup (UMENG_SKIP_PATH=1 / --skip-path); invoke as: $dir/$INSTALL_NAME"
    return 0
  fi

  local already=0
  case ":$PATH:" in
    *:"$dir":*) already=1 ;;
  esac

  if [ "$already" -eq 0 ]; then
    export PATH="$dir:$PATH"
    info "Prepended $dir to PATH for this install session"
  fi

  local marker="# umeng-cli: add install dir to PATH (install.sh)"
  local line_export="export PATH=\"$dir:\$PATH\""
  local rc=""

  case "${SHELL:-}" in
    */zsh) rc="$HOME/.zshrc" ;;
    */bash) rc="$HOME/.bashrc" ;;
    *) rc="$HOME/.profile" ;;
  esac

  if [ -f "$rc" ] && grep -F "$marker" "$rc" >/dev/null 2>&1; then
    info "PATH hook already present in $rc"
    return 0
  fi

  if [ "$already" -eq 1 ]; then
    return 0
  fi

  {
    printf '\n%s\n' "$marker"
    printf '%s\n' "$line_export"
  } >>"$rc" || {
    warn "Could not append to $rc; add PATH yourself: $line_export"
    return 0
  }
  success "Added $dir to PATH via $rc (open a new terminal, or: . $rc)"
}

# ── Skills install ───────────────────────────────────────────────────────

install_skills() {
  if [ "$NO_SKILLS" = "1" ]; then
    info "Skipping skills installation (UMENG_NO_SKILLS=1 / --no-skills)"
    return 0
  fi

  local install_target="$1"
  if [ ! -x "$install_target" ]; then
    warn "Binary not found at $install_target, skipping skills installation"
    return 0
  fi

  info "Installing skills..."
  if "$install_target" skills install umeng-cli; then
    success "Skills installed"
  else
    warn "Skills installation failed. You can install manually later with:"
    warn "  $install_target skills install umeng-cli"
  fi
}

# ── Banner ───────────────────────────────────────────────────────────────

print_banner() {
  printf '\n'
  info "┌────────────────────────────────────────┐"
  info "│     umeng-cli Installer                │"
  info "│     友盟命令行工具                     │"
  info "└────────────────────────────────────────┘"
  printf '\n'
}

# ── Detect conflicting npm installation ──────────────────────────────────

detect_npm_installation() {
  local npm_bin=""

  if ! need_cmd npm; then
    return 1
  fi

  # npm bin -g 在 npm 9+ 已废弃且会输出多行错误信息；
  # 改用 npm config get prefix，并清理换行/空格，避免路径解析错误。
  npm_bin=""
  if npm_prefix="$(npm config get prefix 2>/dev/null | tr -d '\n\r')"; then
    npm_bin="${npm_prefix}/bin"
  fi

  if [ -n "$npm_bin" ] && [ -f "${npm_bin}/umeng-cli" ]; then
    warn "检测到 npm 已安装 umeng-cli：${npm_bin}/umeng-cli"
    warn "继续 shell 安装将产生两个并存版本，可能导致 PATH 冲突。"
    warn "建议先卸载 npm 版本："
    warn "  npm uninstall -g @umengfe/umeng-cli"
    printf '\n'
    return 0
  fi

  # 也检查 node_modules 中是否存在平台包（开发/本地安装场景）
  if [ -d "./node_modules/@umengfe/umeng-cli" ] || [ -d "./node_modules/@umengfe/umeng-cli-darwin-arm64" ]; then
    warn "检测到当前目录存在 npm 安装的 umeng-cli"
    warn "建议只保留一种安装方式，避免版本混乱。"
    printf '\n'
    return 0
  fi

  return 1
}

# ── Install binary ───────────────────────────────────────────────────────

install_binary() {
  local platform="$1"
  local versions_url="${OSS_BASE_URL}/${VERSIONS_FILE}"
  local tmpdir target_version download_url expected_checksum
  local tmp_bin install_target

  info "Reading version info ${VERSION} (${platform})..."

  tmpdir="$(mktemp -d)"
  trap '[ -n "${tmpdir:-}" ] && rm -rf "$tmpdir"' EXIT INT TERM

  if ! download "$versions_url" "$tmpdir/versions.json"; then
    error "Failed to download version info: $versions_url"
  fi

  if [ "$VERSION" = "latest" ]; then
    target_version="$(parse_json_field "$tmpdir/versions.json" "latest")"
  else
    target_version="$VERSION"
  fi

  if [ -z "$target_version" ]; then
    error "Could not resolve target version from versions.json"
  fi

  info "Target version: $target_version"

  install_target="${INSTALL_DIR}/${INSTALL_NAME}"

  if [ "$FORCE" != "1" ] && check_installed_version "$install_target" "$target_version"; then
    info "Skipping binary download"
    return 0
  fi

  if [ "$FORCE" = "1" ]; then
    info "--force enabled, re-downloading binary even if versions match"
  fi

  # Resolve download URL and checksum
  local resolved
  resolved="$(resolve_download_info "$tmpdir/versions.json" "$platform" "$target_version")"
  download_url="$(printf '%s\n' "$resolved" | sed -n '1p')"
  expected_checksum="$(printf '%s\n' "$resolved" | sed -n '2p')"

  if [ -z "$download_url" ]; then
    error "No download URL found for platform ${platform} version ${target_version}"
  fi

  info "Downloading ${BIN_NAME} ${target_version} (${platform})..."
  tmp_bin="$tmpdir/${BIN_NAME}"
  if ! download "$download_url" "$tmp_bin"; then
    error "Failed to download binary: $download_url"
  fi

  verify_checksum "$tmp_bin" "$expected_checksum"

  mkdir -p "$INSTALL_DIR" 2>/dev/null || true

  info "Installing to $install_target..."
  if install -m 755 "$tmp_bin" "$install_target" 2>/dev/null; then
    success "Binary installed"
  elif need_cmd sudo; then
    warn "Permission denied, retrying with sudo..."
    sudo mkdir -p "$INSTALL_DIR" 2>/dev/null || true
    sudo install -m 755 "$tmp_bin" "$install_target" || error "Failed to install binary to $install_target"
    success "Binary installed with sudo"
  else
    error "Failed to install binary to $install_target (permission denied, sudo not available)"
  fi

  if need_cmd xattr; then
    xattr -c "$install_target" 2>/dev/null || true
  fi

  if [ -x "$install_target" ]; then
    local installed_version
    installed_version="$("$install_target" --version 2>/dev/null | head -1 | awk '{print $NF}' | sed 's/^v//')" || true
    if [ -n "$installed_version" ] && [ "$installed_version" = "$target_version" ]; then
      success "umeng-cli $target_version installed successfully"
    else
      warn "Version verification: expected $target_version, got ${installed_version:-unknown}"
    fi
  else
    error "Installation verification failed"
  fi
}

# ── Main ─────────────────────────────────────────────────────────────────

main() {
  parse_args "$@"

  info "Starting umeng-cli installation..."

  guard_cwd

  INSTALL_DIR="$(resolve_install_dir)"
  mkdir -p "$INSTALL_DIR" || error "Failed to create install directory: $INSTALL_DIR"

  local platform
  platform="$(detect_platform)"

  print_banner
  # detect_npm_installation 返回 1 仅表示“未检测到 npm 冲突”，是正常流程
  detect_npm_installation || true
  install_binary "$platform"

  local install_target
  install_target="${INSTALL_DIR}/${INSTALL_NAME}"

  install_skills "$install_target"

  ensure_install_dir_in_path "$INSTALL_DIR"

  printf '\n'
  success "Installation complete!"
  info ""
  info "Next steps:"
  info "  $INSTALL_NAME --version          # verify installation"
  info "  $INSTALL_NAME login              # login to UMeng"
  info "  $INSTALL_NAME --help             # explore commands"
  info ""
  info "  沙箱/项目内安装（不修改 PATH）："
  info "    curl -fsSL ${OSS_BASE_URL}/install.sh | sh -s -- --install-dir ./.umeng-cli/bin --skip-path"
  printf '\n'
}

main "$@"
