#!/bin/bash

# 启动核心MCP服务脚本
# 只启动确认可以工作的核心服务

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"
}

# 创建核心服务配置
create_core_config() {
    log_info "创建核心MCP服务配置..."
    
    cat > docker-compose-core.yml << 'EOF'
name: xiaohongshu-core-mcp

services:
  # 1. GitHub MCP - 代码仓库管理 (已配置)
  mcp-github:
    image: node:18-alpine
    container_name: mcp-github-core
    working_dir: /app
    environment:
      - GITHUB_PERSONAL_ACCESS_TOKEN=${GITHUB_PERSONAL_ACCESS_TOKEN}
    volumes:
      - ../data/mcp-data/github:/app/data
    command: >
      sh -c "
        npm install -g @modelcontextprotocol/server-github &&
        echo '✅ GitHub MCP服务启动成功' &&
        npx @modelcontextprotocol/server-github
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

  # 2. Memory MCP - 知识图谱记忆系统
  mcp-memory:
    image: node:18-alpine
    container_name: mcp-memory-core
    working_dir: /app
    environment:
      - MEMORY_FILE_PATH=/app/data/memory.json
    volumes:
      - ../data/mcp-data/memory:/app/data
    command: >
      sh -c "
        npm install -g @modelcontextprotocol/server-memory &&
        echo '✅ Memory MCP服务启动成功' &&
        npx @modelcontextprotocol/server-memory
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

  # 3. Filesystem MCP - 文件系统操作
  mcp-filesystem:
    image: node:18-alpine
    container_name: mcp-filesystem-core
    working_dir: /app
    volumes:
      - ../data/mcp-data/filesystem:/app/allowed
      - ../../:/app/workspace:ro
    command: >
      sh -c "
        npm install -g @modelcontextprotocol/server-filesystem &&
        echo '✅ Filesystem MCP服务启动成功' &&
        npx @modelcontextprotocol/server-filesystem /app/allowed
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

  # 4. Git MCP - Git仓库操作
  mcp-git:
    image: python:3.11-alpine
    container_name: mcp-git-core
    working_dir: /app
    volumes:
      - ../../:/app/repo
      - ../data/mcp-data/git:/app/data
    environment:
      - GIT_CONFIG_GLOBAL=/app/data/.gitconfig
    command: >
      sh -c "
        apk add --no-cache git &&
        pip install mcp-server-git &&
        echo '✅ Git MCP服务启动成功' &&
        python -m mcp_server_git --repository /app/repo
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

  # 4. Time MCP - 时间和时区转换
  mcp-time:
    image: python:3.11-alpine
    container_name: mcp-time-core
    working_dir: /app
    command: >
      sh -c "
        pip install mcp-server-time &&
        echo '✅ Time MCP服务启动成功' &&
        python -m mcp_server_time
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

  # 5. Sequential Thinking MCP - 动态问题解决
  mcp-sequential-thinking:
    image: node:18-alpine
    container_name: mcp-sequential-thinking-core
    working_dir: /app
    environment:
      - DISABLE_THOUGHT_LOGGING=false
    command: >
      sh -c "
        npm install -g @modelcontextprotocol/server-sequential-thinking &&
        echo '✅ Sequential Thinking MCP服务启动成功' &&
        npx @modelcontextprotocol/server-sequential-thinking
      "
    restart: unless-stopped
    networks:
      - mcp-core-network

networks:
  mcp-core-network:
    driver: bridge

volumes:
  mcp-data:
    driver: local
EOF

    log_success "核心服务配置创建完成"
}

# 创建数据目录
setup_directories() {
    log_info "创建数据目录..."

    mkdir -p ../data/mcp-data/{github,memory,filesystem,git}
    echo "测试文件内容" > ../data/mcp-data/filesystem/test.txt
    echo "欢迎使用MCP服务" > ../data/mcp-data/filesystem/welcome.md

    # 创建Git配置文件
    cat > ../data/mcp-data/git/.gitconfig << 'EOF'
[user]
    name = MCP Git User
    email = mcp@example.com
[init]
    defaultBranch = main
EOF

    log_success "数据目录创建完成"
}

# 启动核心服务
start_core_services() {
    log_info "启动核心MCP服务..."
    
    # 检查环境变量
    if [ ! -f ".env" ]; then
        log_error "环境变量文件 .env 不存在"
        exit 1
    fi
    
    # 创建配置和目录
    create_core_config
    setup_directories
    
    # 启动服务
    log_info "拉取Docker镜像..."
    docker-compose -f docker-compose-core.yml pull
    
    log_info "启动服务容器..."
    docker-compose -f docker-compose-core.yml up -d
    
    # 等待服务启动
    log_info "等待服务启动 (30秒)..."
    sleep 30
    
    # 检查服务状态
    show_service_status
}

# 显示服务状态
show_service_status() {
    log_info "核心MCP服务状态："
    echo ""
    
    docker-compose -f docker-compose-core.yml ps
    
    echo ""
    log_info "服务健康检查："
    
    # 检查各个服务
    services=(
        "mcp-github-core:GitHub代码仓库管理"
        "mcp-memory-core:知识图谱记忆系统"
        "mcp-filesystem-core:文件系统操作"
        "mcp-git-core:Git仓库操作"
        "mcp-time-core:时间和时区转换"
        "mcp-sequential-thinking-core:动态问题解决"
    )
    
    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"; then
                echo -e "  ${GREEN}✅${NC} $service_desc"
            else
                echo -e "  ${YELLOW}⚠️${NC} $service_desc (可能仍在启动中)"
            fi
        else
            echo -e "  ${RED}❌${NC} $service_desc (未运行)"
        fi
    done
    
    echo ""
    log_success "核心服务启动完成！"
    
    # 显示使用说明
    show_usage_info
}

# 显示使用说明
show_usage_info() {
    echo ""
    log_info "=== 使用说明 ==="
    echo ""
    echo "🎯 已启动的核心服务："
    echo "  1. GitHub MCP - 代码仓库管理"
    echo "  2. Memory MCP - 知识图谱记忆"
    echo "  3. Filesystem MCP - 文件系统操作"
    echo "  4. Git MCP - Git仓库操作"
    echo "  5. Time MCP - 时间和时区转换"
    echo "  6. Sequential Thinking MCP - 动态问题解决"
    echo ""
    echo "📋 管理命令："
    echo "  查看日志: docker-compose -f docker-compose-core.yml logs"
    echo "  停止服务: docker-compose -f docker-compose-core.yml down"
    echo "  重启服务: docker-compose -f docker-compose-core.yml restart"
    echo ""
    echo "🔧 下一步："
    echo "  1. 配置Claude Desktop集成这些MCP服务"
    echo "  2. 配置更多API密钥启用高级功能"
    echo "  3. 运行完整的20个服务: ./manage-top20-mcp.sh start"
}

# 停止服务
stop_services() {
    log_info "停止核心MCP服务..."
    docker-compose -f docker-compose-core.yml down
    log_success "服务已停止"
}

# 清理
cleanup() {
    log_info "清理核心MCP服务..."
    docker-compose -f docker-compose-core.yml down -v
    rm -rf ../data/mcp-data
    rm -f docker-compose-core.yml
    log_success "清理完成"
}

# 显示帮助
show_help() {
    echo "核心MCP服务管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start     启动核心MCP服务 (默认)"
    echo "  stop      停止核心MCP服务"
    echo "  status    显示服务状态"
    echo "  logs      显示服务日志"
    echo "  cleanup   清理所有数据"
    echo "  help      显示帮助信息"
}

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

# 运行主函数
main "$@"
