#!/bin/bash

# TOP 20 MCP服务管理脚本
# 管理对开发最有帮助的20个MCP服务

set -e

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

# 配置文件
COMPOSE_FILE="docker-compose-top20-mcp.yml"
ENV_FILE=".env"

# 日志函数
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"
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    if [ ! -f "$ENV_FILE" ]; then
        log_error "环境变量文件 $ENV_FILE 不存在"
        exit 1
    fi
    
    log_success "依赖检查完成"
}

# 创建必要的目录
setup_directories() {
    log_info "创建数据目录..."
    
    mkdir -p mcp-data/{github,memory,filesystem,sqlite}
    chmod 755 mcp-data
    chmod 755 mcp-data/*
    
    log_success "目录创建完成"
}

# 显示服务状态
show_status() {
    log_info "TOP 20 MCP服务状态："
    echo ""
    
    # 检查Docker Compose服务状态
    if docker-compose -f "$COMPOSE_FILE" ps --services --filter "status=running" &> /dev/null; then
        docker-compose -f "$COMPOSE_FILE" ps
    else
        log_warning "没有运行中的服务"
    fi
    
    echo ""
    log_info "服务健康检查："
    
    # 定义服务列表
    services=(
        "mcp-github:GitHub代码仓库管理"
        "mcp-memory:知识图谱记忆系统"
        "mcp-filesystem:文件系统操作"
        "mcp-git:Git仓库操作"
        "mcp-fetch:网页内容获取"
        "mcp-brave-search:网络搜索"
        "mcp-postgres:PostgreSQL数据库"
        "mcp-slack:Slack团队协作"
        "mcp-puppeteer:浏览器自动化"
        "mcp-sqlite:SQLite轻量级数据库"
        "mcp-time:时间和时区转换"
        "mcp-gdrive:Google Drive云存储"
        "mcp-sentry:Sentry错误监控"
        "mcp-redis:Redis缓存系统"
        "mcp-google-maps:Google Maps地图服务"
        "mcp-everart:EverArt AI图像生成"
        "mcp-aws-kb:AWS知识库检索"
        "mcp-gitlab:GitLab项目管理"
        "mcp-sequential-thinking:动态问题解决"
        "mcp-everything:测试和参考服务器"
    )
    
    for service_info in "${services[@]}"; do
        IFS=':' read -r service_name service_desc <<< "$service_info"
        if docker-compose -f "$COMPOSE_FILE" ps "$service_name" | grep -q "Up"; then
            echo -e "  ${GREEN}✓${NC} $service_desc ($service_name)"
        else
            echo -e "  ${RED}✗${NC} $service_desc ($service_name)"
        fi
    done
}

# 启动所有服务
start_services() {
    log_info "启动TOP 20 MCP服务..."
    
    check_dependencies
    setup_directories
    
    # 拉取镜像
    log_info "拉取Docker镜像..."
    docker-compose -f "$COMPOSE_FILE" pull
    
    # 启动服务
    log_info "启动服务..."
    docker-compose -f "$COMPOSE_FILE" up -d
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 10
    
    log_success "所有服务启动完成！"
    show_status
}

# 停止所有服务
stop_services() {
    log_info "停止TOP 20 MCP服务..."
    
    docker-compose -f "$COMPOSE_FILE" down
    
    log_success "所有服务已停止"
}

# 重启所有服务
restart_services() {
    log_info "重启TOP 20 MCP服务..."
    
    stop_services
    sleep 2
    start_services
}

# 查看服务日志
show_logs() {
    local service_name="$1"
    
    if [ -z "$service_name" ]; then
        log_info "显示所有服务日志..."
        docker-compose -f "$COMPOSE_FILE" logs -f --tail=50
    else
        log_info "显示 $service_name 服务日志..."
        docker-compose -f "$COMPOSE_FILE" logs -f --tail=50 "$service_name"
    fi
}

# 清理数据
cleanup() {
    log_warning "这将删除所有MCP数据，确定要继续吗？(y/N)"
    read -r response
    
    if [[ "$response" =~ ^[Yy]$ ]]; then
        log_info "清理MCP数据..."
        
        # 停止服务
        docker-compose -f "$COMPOSE_FILE" down -v
        
        # 删除数据目录
        rm -rf mcp-data
        
        # 清理Docker镜像
        docker system prune -f
        
        log_success "清理完成"
    else
        log_info "取消清理操作"
    fi
}

# 显示帮助信息
show_help() {
    echo "TOP 20 MCP服务管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start     启动所有MCP服务"
    echo "  stop      停止所有MCP服务"
    echo "  restart   重启所有MCP服务"
    echo "  status    显示服务状态"
    echo "  logs      显示所有服务日志"
    echo "  logs <服务名>  显示指定服务日志"
    echo "  cleanup   清理所有数据"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 start                    # 启动所有服务"
    echo "  $0 logs mcp-github         # 查看GitHub MCP日志"
    echo "  $0 status                  # 查看服务状态"
}

# 主函数
main() {
    case "${1:-help}" in
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        status)
            show_status
            ;;
        logs)
            show_logs "$2"
            ;;
        cleanup)
            cleanup
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
