#!/bin/bash

# MCP服务统一管理脚本
# 提供所有MCP服务的启动、停止、状态查看等功能

set -e

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

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PYTHON_CMD="python3"

# 日志函数
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_header() {
    echo -e "${CYAN}$1${NC}"
}

# 检查Python环境
check_python_env() {
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 未安装"
        exit 1
    fi
    
    # 检查虚拟环境
    if [[ -d "$PROJECT_ROOT/.venv" ]]; then
        log_info "检测到虚拟环境，激活中..."
        source "$PROJECT_ROOT/.venv/bin/activate"
    fi
}

# 启动单个服务
start_service() {
    local service_name="$1"
    log_info "启动服务: $service_name"
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py start "$service_name"
}

# 停止单个服务
stop_service() {
    local service_name="$1"
    log_info "停止服务: $service_name"
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py stop "$service_name"
}

# 重启单个服务
restart_service() {
    local service_name="$1"
    log_info "重启服务: $service_name"
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py restart "$service_name"
}

# 启动所有服务
start_all_services() {
    log_header "🚀 启动所有MCP服务"
    echo "=================================================="
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py start-all
    
    log_success "所有服务启动完成"
}

# 停止所有服务
stop_all_services() {
    log_header "🛑 停止所有MCP服务"
    echo "=================================================="
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py stop-all
    
    log_success "所有服务停止完成"
}

# 查看服务状态
show_status() {
    local service_name="$1"
    
    if [[ -n "$service_name" ]]; then
        log_info "查看服务状态: $service_name"
        cd "$PROJECT_ROOT"
        $PYTHON_CMD src/utils/mcp_service_manager.py status "$service_name"
    else
        log_header "📊 MCP服务状态概览"
        echo "=================================================="
        cd "$PROJECT_ROOT"
        $PYTHON_CMD src/utils/mcp_service_manager.py status
    fi
}

# 显示仪表板
show_dashboard() {
    log_header "📊 MCP服务管理仪表板"
    echo "=================================================="
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py dashboard
}

# 启动监控
start_monitoring() {
    log_header "📊 启动MCP服务监控"
    echo "=================================================="
    log_info "按 Ctrl+C 停止监控"
    
    cd "$PROJECT_ROOT"
    $PYTHON_CMD src/utils/mcp_service_manager.py monitor
}

# 健康检查
health_check() {
    log_header "🏥 MCP服务健康检查"
    echo "=================================================="
    
    # 检查核心服务
    local services=("voice-clone-mcp" "exa-mcp" "context7-mcp")
    local healthy_count=0
    local total_count=${#services[@]}
    
    for service in "${services[@]}"; do
        log_info "检查服务: $service"
        
        # 获取服务端口
        local port
        case $service in
            "voice-clone-mcp") port=9020 ;;
            "exa-mcp") port=9021 ;;
            "context7-mcp") port=9022 ;;
            *) port=9000 ;;
        esac
        
        # 检查端口是否开放
        if curl -s "http://localhost:$port/health" > /dev/null 2>&1; then
            log_success "✅ $service (端口 $port) - 健康"
            ((healthy_count++))
        else
            log_warning "❌ $service (端口 $port) - 离线"
        fi
    done
    
    echo ""
    log_info "健康检查完成: $healthy_count/$total_count 服务正常运行"
    
    if [[ $healthy_count -eq $total_count ]]; then
        log_success "🎉 所有核心服务运行正常！"
        return 0
    else
        log_warning "⚠️  部分服务离线，请检查服务状态"
        return 1
    fi
}

# 快速启动核心服务
quick_start() {
    log_header "⚡ 快速启动核心MCP服务"
    echo "=================================================="
    
    # 启动声音克隆MCP服务（核心服务）
    log_info "启动核心服务: voice-clone-mcp"
    start_service "voice-clone-mcp"
    
    # 等待服务启动
    sleep 3
    
    # 健康检查
    if health_check; then
        log_success "🚀 核心服务启动完成！"
        
        echo ""
        log_info "🔗 服务访问地址:"
        echo "   • 声音克隆MCP: http://localhost:9020"
        echo "   • API文档: http://localhost:9020/docs"
        echo "   • 健康检查: http://localhost:9020/health"
        
        echo ""
        log_info "💡 使用提示:"
        echo "   • 查看状态: $0 status"
        echo "   • 启动仪表板: $0 dashboard"
        echo "   • 启动监控: $0 monitor"
    else
        log_error "❌ 核心服务启动失败，请检查日志"
        return 1
    fi
}

# 显示帮助信息
show_help() {
    echo -e "${CYAN}MCP服务统一管理脚本${NC}"
    echo "=================================================="
    echo ""
    echo "用法: $0 <command> [service_name]"
    echo ""
    echo "命令:"
    echo "  start <service>     启动指定服务"
    echo "  stop <service>      停止指定服务"
    echo "  restart <service>   重启指定服务"
    echo "  start-all          启动所有服务"
    echo "  stop-all           停止所有服务"
    echo "  status [service]   查看服务状态"
    echo "  dashboard          显示管理仪表板"
    echo "  monitor            启动服务监控"
    echo "  health             健康检查"
    echo "  quick-start        快速启动核心服务"
    echo "  help               显示帮助信息"
    echo ""
    echo "可用服务:"
    echo "  voice-clone-mcp    声音克隆MCP服务"
    echo "  exa-mcp           Exa搜索MCP服务"
    echo "  context7-mcp      Context7文档MCP服务"
    echo "  semgrep-mcp       Semgrep安全检测MCP服务"
    echo "  ast-grep-mcp      AST-Grep代码分析MCP服务"
    echo "  graphql-forge-mcp GraphQL Forge API设计MCP服务"
    echo "  database-mcp      数据库连接MCP服务"
    echo "  apify-mcp         Apify数据抓取MCP服务"
    echo "  task-master-mcp   任务管理MCP服务"
    echo ""
    echo "示例:"
    echo "  $0 quick-start              # 快速启动核心服务"
    echo "  $0 start voice-clone-mcp    # 启动声音克隆服务"
    echo "  $0 status                   # 查看所有服务状态"
    echo "  $0 dashboard                # 显示管理仪表板"
    echo ""
}

# 主函数
main() {
    # 检查Python环境
    check_python_env
    
    # 解析命令
    case "${1:-help}" in
        "start")
            if [[ -n "$2" ]]; then
                start_service "$2"
            else
                log_error "请指定服务名称"
                echo "用法: $0 start <service_name>"
                exit 1
            fi
            ;;
        "stop")
            if [[ -n "$2" ]]; then
                stop_service "$2"
            else
                log_error "请指定服务名称"
                echo "用法: $0 stop <service_name>"
                exit 1
            fi
            ;;
        "restart")
            if [[ -n "$2" ]]; then
                restart_service "$2"
            else
                log_error "请指定服务名称"
                echo "用法: $0 restart <service_name>"
                exit 1
            fi
            ;;
        "start-all")
            start_all_services
            ;;
        "stop-all")
            stop_all_services
            ;;
        "status")
            show_status "$2"
            ;;
        "dashboard")
            show_dashboard
            ;;
        "monitor")
            start_monitoring
            ;;
        "health")
            health_check
            ;;
        "quick-start")
            quick_start
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"