#!/usr/bin/env bash
#============================================================
# File: vibe-coding.sh
# Description: 安装和配置 vibe-coding CLI 工具
# Author: Jetsung Chan <i@jetsung.com>
# Version: 0.1.0
# UpdatedAt: 2026-01-21
#============================================================

log() {
  # 蓝色粗体
  printf "\033[1;34m[INFO]\033[0m %s\n" "$*" >&2
}

warn() {
  # 黄色
  printf "\033[1;33m[WARN]\033[0m %s\n" "$*" >&2
}

error() {
  # 红色
  printf "\033[1;31m[ERROR]\033[0m %s\n" "$*" >&2
}

success() {
  printf "\033[1;32m[SUCCESS]\033[0m %s\n" "$*" >&2
}

sep() {
  printf "\033[1;35m========== %s ==========\033[0m\n" "$*" >&2
}

check_command() {
  local cmd="$1"
  local name="$2"

  if ! command -v "$cmd" &> /dev/null; then
    error "$name is not installed. Please install $name first."
    exit 1
  fi
}

check_in_china() {
    if [[ -n "${CN:-}" ]]; then
        return 0 # 手动指定
    fi
    if [[ "$(curl -s -m 3 -o /dev/null -w "%{http_code}" https://www.google.com)" == "000" ]]; then
        return 0 # 中国网络
    fi
    return 1 # 非中国网络
}

npm_packages() {
  check_command "npm" "npm"

  packages=(
    "@openai/codex"
    "@google/gemini-cli"
    "@qwen-code/qwen-code"
    "@tencent-ai/codebuddy-code"
    "@kilocode/cli"
    "@musistudio/claude-code-router"
    "@anthropic-ai/claude-code"
  )

  echo
  for pkg in "${packages[@]}"; do
    sep "Installing $pkg"
    npm install -g "$pkg"
    success "$pkg"
  done
}

spec() {
  check_command "npm" "npm"
  check_command "uv" "uv"

  echo
  sep "Installing @fission-ai/openspec"
  npm install -g @fission-ai/openspec
  success "@fission-ai/openspec"

  sep "Installing spec-kit"
  uv tool install specify-cli --from git+https://github.com/github/spec-kit.git
  success "spec-kit"
}

binary_list() {
  urls=(
    "https://opencode.ai/install"
  )

  echo
  for url in "${urls[@]}"; do
    echo
    sep "$url"
    if [[ -n "${IS_CHINA:-}" ]]; then
      log "curl -fsSL fx4.cn/x | bash -s -- \"$url\" | bash > /dev/null 2>&1"
      curl -fsSL fx4.cn/x | bash -s -- "$url" | bash > /dev/null 2>&1
    else
      log "curl -fsSL \"$url\" | bash"
      curl -fsSL "$url" | bash
    fi
  done

  # no proxy
  urls=(
    "https://cli.kiro.dev/install"
    "https://qoder.com/install"
  )

  echo
  for url in "${urls[@]}"; do
    echo
    sep "$url"
    curl -fsSL "$url" | bash > /dev/null 2>&1
    log "curl -fsSL \"$url\" | bash > /dev/null 2>&1"
  done
}

fix_tools_claude() {
  set -- ~/.claude/downloads/claude-*-linux-x64
  if [ -f "$1" ]; then
    if "$1" --version 2>/dev/null | grep -q "Claude"; then
      mv "$1" ~/.local/bin/claude
    fi
    echo
    success "$(claude --version)"
  fi
}

fix_tools() {
  fix_tools_claude
}

main() {
  if check_in_china; then
    IS_CHINA=1
  fi
  npm_packages
  spec
  binary_list
  fix_tools
}

main "$@"
