#!/bin/bash

# CC Switch - 改进的全局安装脚本
# 使用npm link方式进行全局安装

set -e

CCS_VERSION="1.0.0"

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"

# 检查npm
if ! command -v npm &> /dev/null; then
    echo "❌ npm is required but not installed."
    exit 1
fi

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

# 全局链接
echo "📦 Installing globally..."
npm link

echo "✅ Installation completed!"
echo ""
echo "📝 Installation Summary:"
echo "   Method: npm link"
echo "   Command: ccs"
echo "   Version: $CCS_VERSION"
echo ""

# 测试安装
echo "🧪 Testing installation..."
if ccs --version &> /dev/null; then
    echo "✅ Global installation successful!"
    echo ""
    echo "🎯 You can now use 'ccs' from anywhere!"
else
    echo "⚠️  Global installation may have issues"
    echo ""
    echo "💡 Alternative: Use locally with 'npm start' or 'node dist/cli.js'"
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"