#!/bin/bash

# CC Switch - 全局安装脚本
# 用于将CC Switch工具安装到系统PATH中

set -e

CCS_VERSION="1.0.0"
INSTALL_DIR="$HOME/.local/bin"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "🚀 Installing CC Switch v${CCS_VERSION}"
echo "================================================"

# 检查Node.js
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is required but not installed."
    echo "Please install Node.js 18+ and try again."
    exit 1
fi

NODE_VERSION=$(node -v | sed 's/v//')
NODE_MAJOR_VERSION=$(echo $NODE_VERSION | cut -d. -f1)

if [ "$NODE_MAJOR_VERSION" -lt 18 ]; then
    echo "❌ Node.js 18+ is required. Current version: v${NODE_VERSION}"
    echo "Please upgrade Node.js and try again."
    exit 1
fi

echo "✅ Node.js ${NODE_VERSION} detected"

# 创建安装目录
mkdir -p "$INSTALL_DIR"

# 构建项目
echo "🔧 Building project..."
npm run build

# 复制文件到安装目录
echo "📦 Installing files..."
cp -r dist/ "$INSTALL_DIR/ccs-dist"
cp package.json "$INSTALL_DIR/ccs-dist/"
cp -r node_modules/ "$INSTALL_DIR/ccs-dist/"

# 创建全局命令脚本
cat > "$INSTALL_DIR/ccs" << 'EOF'
#!/usr/bin/env bash
cd "$HOME/.local/bin/ccs-dist"
node cli.js "$@"
EOF

chmod +x "$INSTALL_DIR/ccs"

echo "✅ Installation completed!"
echo ""
echo "📝 Installation Summary:"
echo "   Install directory: $INSTALL_DIR"
echo "   Command: ccs"
echo "   Version: $CCS_VERSION"
echo ""

# 检查PATH
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    echo "⚠️  $INSTALL_DIR is not in your PATH"
    echo ""
    echo "💡 To use 'ccs' globally, add this line to your shell profile:"
    echo "   echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.bashrc"
    echo "   echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc"
    echo ""
    echo "Then restart your terminal or run:"
    echo "   source ~/.bashrc  # or ~/.zshrc"
    echo ""
    echo "🔧 Or run directly with full path:"
    echo "   $INSTALL_DIR/ccs"
else
    echo "✅ $INSTALL_DIR is already in your PATH"
    echo ""
    echo "🎯 You can now use 'ccs' from anywhere!"
fi

echo ""
echo "🚀 Quick start:"
echo "   ccs --help                           # Show help"
echo "   ccs diagnostics                      # Check system status"
echo "   ccs add dev https://api.example.com sk-xxx  # Add configuration"
echo "   ccs switch dev                       # Switch to configuration"
echo ""
echo "📚 For more information, run: ccs --help"