#!/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'
NC='\033[0m' # No Color

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

# 检查Docker是否运行
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        log_error "Docker未运行，请先启动Docker"
        exit 1
    fi
    log_success "Docker运行正常"
}

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        log_warning "端口 $port 已被占用"
        return 1
    else
        log_success "端口 $port 可用"
        return 0
    fi
}

# 检查必要的目录
check_directories() {
    local base_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    
    # 检查必要目录
    local dirs=(
        "$base_dir/voice-clone"
        "$base_dir/data/mcp-data"
        "$base_dir/docker"
    )
    
    for dir in "${dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            log_warning "目录不存在，正在创建: $dir"
            mkdir -p "$dir"
        fi
    done
    
    log_success "目录检查完成"
}

# 创建数据目录
create_data_directories() {
    local base_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    local data_dirs=(
        "$base_dir/data/mcp-data/voice-clone"
        "$base_dir/voice-clone/voice-clone-mcp/cache"
        "$base_dir/voice-clone/voice-clone-mcp/logs"
        "$base_dir/voice-clone/voice-clone-mcp/temp"
    )
    
    for dir in "${data_dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            log_info "创建数据目录: $dir"
        fi
    done
    
    log_success "数据目录创建完成"
}

# 检查环境变量
check_environment() {
    log_info "检查环境变量..."
    
    # 检查.env文件
    local env_file="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/voice-clone/voice-clone-mcp/.env"
    
    if [ ! -f "$env_file" ]; then
        log_warning ".env文件不存在，从.env.example复制"
        local example_file="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/voice-clone/voice-clone-mcp/.env.example"
        if [ -f "$example_file" ]; then
            cp "$example_file" "$env_file"
            log_success "已创建.env文件"
        else
            log_error ".env.example文件不存在"
            return 1
        fi
    fi
    
    log_success "环境变量检查完成"
}

# 构建Docker镜像
build_image() {
    log_info "构建声音克隆MCP Docker镜像..."
    
    local base_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    local build_context="$base_dir/voice-clone/voice-clone-mcp"
    
    if [ ! -f "$build_context/Dockerfile" ]; then
        log_error "Dockerfile不存在: $build_context/Dockerfile"
        return 1
    fi
    
    # 构建镜像
    docker build -t voice-clone-mcp:latest "$build_context"
    
    if [ $? -eq 0 ]; then
        log_success "Docker镜像构建成功"
    else
        log_error "Docker镜像构建失败"
        return 1
    fi
}

# 启动服务
start_service() {
    log_info "启动声音克隆MCP服务..."
    
    local base_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    local compose_file="$base_dir/docker/docker-compose.voice-clone-mcp.yml"
    
    if [ ! -f "$compose_file" ]; then
        log_error "Docker Compose文件不存在: $compose_file"
        return 1
    fi
    
    # 启动服务
    cd "$base_dir/docker"
    docker-compose -f docker-compose.voice-clone-mcp.yml up -d
    
    if [ $? -eq 0 ]; then
        log_success "声音克隆MCP服务启动成功"
    else
        log_error "声音克隆MCP服务启动失败"
        return 1
    fi
}

# 检查服务状态
check_service_status() {
    log_info "检查服务状态..."
    
    # 等待服务启动
    sleep 10
    
    # 检查容器状态
    if docker ps | grep -q "mcp-voice-clone"; then
        log_success "容器运行正常"
    else
        log_error "容器未运行"
        return 1
    fi
    
    # 检查健康状态
    local health_url="http://localhost:9020/health"
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s "$health_url" > /dev/null 2>&1; then
            log_success "服务健康检查通过"
            return 0
        fi
        
        log_info "等待服务启动... ($attempt/$max_attempts)"
        sleep 2
        ((attempt++))
    done
    
    log_error "服务健康检查失败"
    return 1
}

# 显示服务信息
show_service_info() {
    echo ""
    log_success "🎤 声音克隆MCP服务启动完成！"
    echo ""
    echo -e "${CYAN}📋 服务信息:${NC}"
    echo "  • 服务名称: 声音克隆MCP服务"
    echo "  • 容器名称: mcp-voice-clone"
    echo "  • 主端口: 9020"
    echo "  • 健康检查: http://localhost:9020/health"
    echo "  • API文档: http://localhost:9020/docs"
    echo "  • MCP端点: http://localhost:9020/mcp"
    echo ""
    echo -e "${CYAN}🔧 可用工具:${NC}"
    echo "  • generate_voice - 基础语音生成"
    echo "  • generate_voice_with_reference - 参考音频语音克隆"
    echo "  • batch_generate_voice - 批量语音生成"
    echo "  • voice_style_transfer - 语音风格迁移"
    echo "  • get_voice_service_info - 获取服务信息"
    echo "  • test_voice_generation - 测试语音生成"
    echo ""
    echo -e "${CYAN}📋 管理命令:${NC}"
    echo "  查看日志: docker-compose -f docker-compose.voice-clone-mcp.yml logs"
    echo "  停止服务: docker-compose -f docker-compose.voice-clone-mcp.yml down"
    echo "  重启服务: docker-compose -f docker-compose.voice-clone-mcp.yml restart"
    echo ""
    echo -e "${CYAN}🌍 支持的语言:${NC}"
    echo "  中文(zh-cn), 英语(en), 日语(ja), 韩语(ko), 西班牙语(es)"
    echo "  法语(fr), 德语(de), 意大利语(it), 葡萄牙语(pt), 俄语(ru)"
    echo ""
    echo -e "${CYAN}😊 支持的情感:${NC}"
    echo "  中性(neutral), 快乐(happy), 悲伤(sad), 愤怒(angry)"
    echo "  兴奋(excited), 平静(calm), 惊讶(surprised)"
    echo ""
}

# 主函数
main() {
    echo -e "${PURPLE}🎤 声音克隆MCP服务启动脚本${NC}"
    echo ""
    
    # 执行检查和启动流程
    check_docker
    check_directories
    create_data_directories
    check_environment
    
    # 检查端口
    if ! check_port 9020; then
        log_error "端口9020被占用，请先停止占用该端口的服务"
        exit 1
    fi
    
    # 构建和启动
    build_image
    start_service
    check_service_status
    
    # 显示信息
    show_service_info
}

# 运行主函数
main "$@"