#!/bin/bash

# 扩展MCP服务启动脚本
# 基于awesome-mcp-servers项目的精选服务

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_highlight() {
    echo -e "${PURPLE}[HIGHLIGHT]${NC} $1"
}

# 显示服务介绍
show_service_intro() {
    echo ""
    log_highlight "🌟 扩展MCP服务集群 - 基于awesome-mcp-servers精选"
    echo ""
    echo "📦 包含12个高价值MCP服务："
    echo ""
    echo "🔧 核心服务 (3个):"
    echo "  1. GitHub MCP - 代码仓库管理"
    echo "  2. Memory MCP - 知识图谱记忆"
    echo "  3. Filesystem MCP - 文件系统操作"
    echo ""
    echo "🚀 扩展服务 (9个):"
    echo "  4. Brave Search MCP - 网络搜索"
    echo "  5. Fetch MCP - 网页内容获取"
    echo "  6. YouTube MCP - 视频内容分析"
    echo "  7. ArXiv MCP - 学术论文搜索"
    echo "  8. OpenAI MCP - AI模型调用"
    echo "  9. Calculator MCP - 数学计算"
    echo "  10. Wolfram Alpha MCP - 计算知识引擎"
    echo "  11. Notion MCP - 知识管理"
    echo "  12. Linear MCP - 项目管理"
    echo ""
}

# 检查API密钥配置
check_api_keys() {
    log_info "检查API密钥配置..."
    
    # 必需的API密钥
    required_keys=(
        "GITHUB_PERSONAL_ACCESS_TOKEN:GitHub代码仓库"
    )
    
    # 可选的API密钥
    optional_keys=(
        "BRAVE_API_KEY:Brave搜索"
        "OPENAI_API_KEY:OpenAI模型"
        "WOLFRAM_ALPHA_APPID:Wolfram Alpha"
        "NOTION_TOKEN:Notion知识管理"
        "LINEAR_API_KEY:Linear项目管理"
    )
    
    echo ""
    log_info "✅ 必需的API密钥状态:"
    for key_info in "${required_keys[@]}"; do
        IFS=':' read -r key_name service_name <<< "$key_info"
        if grep -q "^${key_name}=.*[^_here]$" .env 2>/dev/null; then
            echo "  ✅ $service_name - 已配置"
        else
            echo "  ❌ $service_name - 未配置"
        fi
    done
    
    echo ""
    log_info "⚡ 可选的API密钥状态:"
    for key_info in "${optional_keys[@]}"; do
        IFS=':' read -r key_name service_name <<< "$key_info"
        if grep -q "^${key_name}=.*[^_here]$" .env 2>/dev/null; then
            echo "  ✅ $service_name - 已配置"
        else
            echo "  ⏳ $service_name - 未配置 (可选)"
        fi
    done
    
    echo ""
    log_info "💡 无需API密钥的服务:"
    echo "  ✅ Memory MCP - 知识图谱记忆"
    echo "  ✅ Filesystem MCP - 文件系统操作"
    echo "  ✅ Fetch MCP - 网页内容获取"
    echo "  ✅ YouTube MCP - 视频内容分析"
    echo "  ✅ ArXiv MCP - 学术论文搜索"
    echo "  ✅ Calculator MCP - 数学计算"
}

# 创建数据目录
setup_directories() {
    log_info "创建数据目录..."
    
    mkdir -p mcp-data/{github,memory,filesystem}
    
    # 创建示例文件
    echo "# 欢迎使用扩展MCP服务" > mcp-data/filesystem/README.md
    echo "这是一个基于awesome-mcp-servers项目精选的MCP服务集群。" >> mcp-data/filesystem/README.md
    echo "" >> mcp-data/filesystem/README.md
    echo "## 功能特性" >> mcp-data/filesystem/README.md
    echo "- 🔍 智能搜索 (Brave Search)" >> mcp-data/filesystem/README.md
    echo "- 🧠 AI模型调用 (OpenAI)" >> mcp-data/filesystem/README.md
    echo "- 📚 学术研究 (ArXiv)" >> mcp-data/filesystem/README.md
    echo "- 🎥 视频分析 (YouTube)" >> mcp-data/filesystem/README.md
    echo "- 🧮 数学计算 (Calculator + Wolfram)" >> mcp-data/filesystem/README.md
    echo "- 📝 知识管理 (Notion)" >> mcp-data/filesystem/README.md
    echo "- 📋 项目管理 (Linear)" >> mcp-data/filesystem/README.md
    
    log_success "数据目录创建完成"
}

# 启动扩展服务
start_extended_services() {
    show_service_intro
    check_api_keys
    
    # 检查环境变量文件
    if [ ! -f ".env" ]; then
        log_error "环境变量文件 .env 不存在"
        exit 1
    fi
    
    setup_directories
    
    log_info "启动扩展MCP服务集群..."
    
    # 拉取镜像
    log_info "拉取Docker镜像..."
    docker-compose -f docker-compose-extended-mcp.yml pull
    
    # 启动服务
    log_info "启动服务容器..."
    docker-compose -f docker-compose-extended-mcp.yml up -d
    
    # 等待服务启动
    log_info "等待服务启动 (45秒)..."
    sleep 45
    
    # 检查服务状态
    show_service_status
}

# 显示服务状态
show_service_status() {
    log_info "扩展MCP服务状态："
    echo ""
    
    docker-compose -f docker-compose-extended-mcp.yml ps
    
    echo ""
    log_info "服务健康检查："
    
    # 检查各个服务
    services=(
        "mcp-github-ext:GitHub代码仓库管理"
        "mcp-memory-ext:知识图谱记忆系统"
        "mcp-filesystem-ext:文件系统操作"
        "mcp-brave-search-ext:Brave网络搜索"
        "mcp-fetch-ext:网页内容获取"
        "mcp-youtube-ext:YouTube视频分析"
        "mcp-arxiv-ext:ArXiv学术论文"
        "mcp-openai-ext:OpenAI模型调用"
        "mcp-calculator-ext:数学计算器"
        "mcp-wolfram-ext:Wolfram Alpha"
        "mcp-notion-ext:Notion知识管理"
        "mcp-linear-ext:Linear项目管理"
    )
    
    for service_info in "${services[@]}"; do
        IFS=':' read -r service_name service_desc <<< "$service_info"
        if docker ps | grep -q "$service_name"; then
            if docker logs "$service_name" 2>&1 | grep -q "启动成功\|listening\|ready\|started\|running"; then
                echo "  ✅ $service_desc"
            else
                echo "  ⚠️ $service_desc (启动中...)"
            fi
        else
            echo "  ❌ $service_desc (未运行)"
        fi
    done
    
    echo ""
    log_success "扩展MCP服务集群启动完成！"
    
    # 显示使用说明
    show_usage_info
}

# 显示使用说明
show_usage_info() {
    echo ""
    log_highlight "=== 🎯 使用指南 ==="
    echo ""
    echo "📋 管理命令："
    echo "  查看状态: ./start-extended-mcp.sh status"
    echo "  查看日志: docker-compose -f docker-compose-extended-mcp.yml logs"
    echo "  停止服务: docker-compose -f docker-compose-extended-mcp.yml down"
    echo "  重启服务: docker-compose -f docker-compose-extended-mcp.yml restart"
    echo ""
    echo "🔧 API密钥配置："
    echo "  编辑配置: nano .env"
    echo "  重启生效: ./start-extended-mcp.sh restart"
    echo ""
    echo "🚀 Claude Desktop集成："
    echo "  配置文件: claude_desktop_config_extended.json"
    echo "  重启Claude: 重启Claude Desktop应用"
    echo ""
    echo "📖 服务文档："
    echo "  详细分析: cat AWESOME_MCP_ANALYSIS.md"
    echo "  官方列表: https://github.com/punkpeye/awesome-mcp-servers"
    echo ""
    log_highlight "🎉 现在你拥有了一个功能强大的MCP服务生态系统！"
}

# 停止服务
stop_services() {
    log_info "停止扩展MCP服务..."
    docker-compose -f docker-compose-extended-mcp.yml down
    log_success "服务已停止"
}

# 重启服务
restart_services() {
    log_info "重启扩展MCP服务..."
    stop_services
    sleep 3
    start_extended_services
}

# 显示帮助
show_help() {
    echo "扩展MCP服务管理脚本 (基于awesome-mcp-servers)"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start     启动扩展MCP服务 (默认)"
    echo "  stop      停止扩展MCP服务"
    echo "  restart   重启扩展MCP服务"
    echo "  status    显示服务状态"
    echo "  logs      显示服务日志"
    echo "  keys      检查API密钥配置"
    echo "  help      显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 start                    # 启动所有扩展服务"
    echo "  $0 keys                     # 检查API密钥配置"
    echo "  $0 status                   # 查看服务状态"
}

# 主函数
main() {
    case "${1:-start}" in
        start)
            start_extended_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        status)
            if [ -f "docker-compose-extended-mcp.yml" ]; then
                show_service_status
            else
                log_error "服务未启动，请先运行: $0 start"
            fi
            ;;
        logs)
            if [ -f "docker-compose-extended-mcp.yml" ]; then
                docker-compose -f docker-compose-extended-mcp.yml logs -f
            else
                log_error "服务未启动，请先运行: $0 start"
            fi
            ;;
        keys)
            check_api_keys
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
