#!/bin/bash
# 🔗 WhatsApp Bridge MCP Docker 安装脚本 (macOS版本)

set -e

# 颜色输出函数
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

print_color() {
    printf "${!1}%s${NC}\n" "$2"
}

print_header() {
    echo ""
    print_color "CYAN" "🔗 WhatsApp Bridge MCP Docker 安装器"
    print_color "CYAN" "================================================"
    print_color "GREEN" "自动化安装 WhatsApp Bridge MCP 到 Docker 环境"
    echo ""
}

# 检查环境依赖
check_environment() {
    print_color "YELLOW" "🔍 检查环境依赖..."
    
    local all_good=true
    
    # 检查Docker
    if command -v docker &> /dev/null; then
        local docker_version=$(docker --version)
        print_color "GREEN" "✅ Docker: $docker_version"
    else
        print_color "RED" "❌ Docker未安装"
        print_color "YELLOW" "请先安装Docker Desktop: https://www.docker.com/products/docker-desktop"
        all_good=false
    fi
    
    # 检查Docker Compose
    if command -v docker-compose &> /dev/null; then
        local compose_version=$(docker-compose --version)
        print_color "GREEN" "✅ Docker Compose: $compose_version"
    else
        print_color "RED" "❌ Docker Compose未安装"
        all_good=false
    fi
    
    # 检查Git
    if command -v git &> /dev/null; then
        local git_version=$(git --version)
        print_color "GREEN" "✅ Git: $git_version"
    else
        print_color "RED" "❌ Git未安装"
        all_good=false
    fi
    
    # 检查网络连接
    if ping -c 1 github.com &> /dev/null; then
        print_color "GREEN" "✅ 网络连接正常"
    else
        print_color "YELLOW" "⚠️ 网络连接可能有问题"
    fi
    
    if [ "$all_good" = false ]; then
        print_color "RED" "❌ 环境检查失败，请解决依赖问题后重试"
        exit 1
    fi
    
    return 0
}

# 安装依赖和克隆仓库
install_dependencies() {
    print_color "YELLOW" "📦 安装依赖和克隆仓库..."
    
    # 检查是否已存在项目目录
    if [ -d "whatsapp-mcp" ]; then
        print_color "BLUE" "📁 项目目录已存在，更新代码..."
        cd whatsapp-mcp
        git pull origin main
        cd ..
    else
        print_color "BLUE" "📥 克隆 WhatsApp MCP 仓库..."
        git clone https://github.com/lharries/whatsapp-mcp.git
        
        if [ ! -d "whatsapp-mcp" ]; then
            print_color "RED" "❌ 克隆仓库失败"
            exit 1
        fi
    fi
    
    # 复制Docker配置文件
    print_color "BLUE" "📋 复制Docker配置文件..."
    
    if [ -f "docker-compose-whatsapp-mcp.yml" ]; then
        cp docker-compose-whatsapp-mcp.yml whatsapp-mcp/docker-compose.yml
        print_color "GREEN" "✅ Docker Compose配置已复制"
    fi
    
    # 创建Dockerfile目录结构
    mkdir -p whatsapp-mcp/whatsapp-bridge
    mkdir -p whatsapp-mcp/whatsapp-mcp-server
    
    if [ -f "whatsapp-bridge/Dockerfile" ]; then
        cp whatsapp-bridge/Dockerfile whatsapp-mcp/whatsapp-bridge/
        print_color "GREEN" "✅ WhatsApp Bridge Dockerfile已复制"
    fi
    
    if [ -f "whatsapp-mcp-server/Dockerfile" ]; then
        cp whatsapp-mcp-server/Dockerfile whatsapp-mcp/whatsapp-mcp-server/
        print_color "GREEN" "✅ MCP Server Dockerfile已复制"
    fi
    
    return 0
}

# 构建Docker镜像
build_docker_images() {
    print_color "YELLOW" "🔨 构建Docker镜像..."
    
    if [ ! -d "whatsapp-mcp" ]; then
        print_color "RED" "❌ 项目目录不存在，请先运行安装依赖"
        exit 1
    fi
    
    cd whatsapp-mcp
    
    print_color "BLUE" "🔨 构建WhatsApp Bridge镜像..."
    docker-compose build whatsapp-bridge
    
    print_color "BLUE" "🔨 构建MCP Server镜像..."
    docker-compose build whatsapp-mcp-server
    
    print_color "GREEN" "✅ Docker镜像构建完成"
    cd ..
    
    return 0
}

# 启动服务
start_services() {
    print_color "YELLOW" "🚀 启动WhatsApp MCP服务..."
    
    if [ ! -d "whatsapp-mcp" ]; then
        print_color "RED" "❌ 项目目录不存在"
        exit 1
    fi
    
    cd whatsapp-mcp
    
    # 创建必要的目录
    mkdir -p whatsapp-bridge/store
    mkdir -p whatsapp-bridge/logs
    mkdir -p whatsapp-mcp-server/logs
    
    print_color "BLUE" "🚀 启动Docker Compose服务..."
    docker-compose up -d
    
    print_color "BLUE" "⏳ 等待服务启动..."
    sleep 10
    
    # 检查服务状态
    print_color "BLUE" "📊 检查服务状态..."
    docker-compose ps
    
    print_color "GREEN" "✅ WhatsApp MCP服务已启动"
    echo ""
    print_color "CYAN" "🔗 服务访问地址:"
    print_color "NC" "  WhatsApp Bridge: http://localhost:8080"
    print_color "NC" "  MCP Server: localhost:9023"
    echo ""
    print_color "YELLOW" "📱 首次使用需要扫描QR码进行WhatsApp认证"
    print_color "YELLOW" "请查看日志获取QR码: ./install-whatsapp-mcp.sh logs"
    
    cd ..
    return 0
}

# 查看服务状态
show_status() {
    print_color "YELLOW" "📊 查看服务状态..."
    
    if [ ! -d "whatsapp-mcp" ]; then
        print_color "RED" "❌ 项目目录不存在"
        exit 1
    fi
    
    cd whatsapp-mcp
    
    print_color "CYAN" "🐳 Docker容器状态:"
    docker-compose ps
    
    echo ""
    print_color "CYAN" "🔍 服务健康检查:"
    
    # 检查WhatsApp Bridge
    if curl -f http://localhost:8080/health &> /dev/null; then
        print_color "GREEN" "✅ WhatsApp Bridge: 健康"
    else
        print_color "RED" "❌ WhatsApp Bridge: 无响应"
    fi
    
    # 检查MCP Server
    if nc -z localhost 9023 &> /dev/null; then
        print_color "GREEN" "✅ MCP Server: 端口开放"
    else
        print_color "RED" "❌ MCP Server: 端口未开放"
    fi
    
    echo ""
    print_color "CYAN" "📈 资源使用情况:"
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}"
    
    cd ..
}

# 查看日志
show_logs() {
    print_color "YELLOW" "📋 查看服务日志..."
    
    if [ ! -d "whatsapp-mcp" ]; then
        print_color "RED" "❌ 项目目录不存在"
        exit 1
    fi
    
    cd whatsapp-mcp
    
    echo "请选择要查看的日志:"
    echo "1. WhatsApp Bridge 日志"
    echo "2. MCP Server 日志"
    echo "3. 所有服务日志"
    
    read -p "请输入选择 (1-3): " choice
    
    case $choice in
        1)
            print_color "CYAN" "📋 WhatsApp Bridge 日志:"
            docker-compose logs -f whatsapp-bridge
            ;;
        2)
            print_color "CYAN" "📋 MCP Server 日志:"
            docker-compose logs -f whatsapp-mcp-server
            ;;
        3)
            print_color "CYAN" "📋 所有服务日志:"
            docker-compose logs -f
            ;;
        *)
            print_color "RED" "❌ 无效选择"
            ;;
    esac
    
    cd ..
}

# 停止服务
stop_services() {
    print_color "YELLOW" "🛑 停止WhatsApp MCP服务..."
    
    if [ ! -d "whatsapp-mcp" ]; then
        print_color "RED" "❌ 项目目录不存在"
        exit 1
    fi
    
    cd whatsapp-mcp
    docker-compose down
    print_color "GREEN" "✅ WhatsApp MCP服务已停止"
    cd ..
}

# 完整安装流程
complete_installation() {
    print_color "GREEN" "🚀 开始完整安装流程..."
    
    # 1. 检查环境
    check_environment
    
    # 2. 安装依赖
    install_dependencies
    
    # 3. 构建镜像
    build_docker_images
    
    # 4. 启动服务
    start_services
    
    print_color "GREEN" "🎉 WhatsApp MCP安装完成！"
    echo ""
    print_color "CYAN" "📱 下一步操作:"
    print_color "NC" "1. 查看日志获取QR码: ./install-whatsapp-mcp.sh logs"
    print_color "NC" "2. 使用WhatsApp扫描QR码完成认证"
    print_color "NC" "3. 在Claude Desktop中配置MCP连接"
    echo ""
    print_color "CYAN" "🔧 MCP配置信息:"
    print_color "NC" "端口: 9023"
    print_color "NC" "服务名: whatsapp"
}

# 显示帮助信息
show_help() {
    print_color "CYAN" "📖 WhatsApp Bridge MCP Docker 安装器使用说明:"
    echo ""
    print_color "YELLOW" "使用方法:"
    print_color "NC" "  ./install-whatsapp-mcp.sh [命令]"
    echo ""
    print_color "YELLOW" "可用命令:"
    print_color "NC" "  install    执行完整安装流程"
    print_color "NC" "  check      检查环境依赖"
    print_color "NC" "  build      构建Docker镜像"
    print_color "NC" "  start      启动服务"
    print_color "NC" "  status     查看服务状态"
    print_color "NC" "  logs       查看服务日志"
    print_color "NC" "  stop       停止服务"
    print_color "NC" "  help       显示帮助信息"
    echo ""
    print_color "YELLOW" "使用示例:"
    print_color "NC" "  ./install-whatsapp-mcp.sh install"
    print_color "NC" "  ./install-whatsapp-mcp.sh status"
    print_color "NC" "  ./install-whatsapp-mcp.sh logs"
}

# 主函数
main() {
    print_header
    
    case "${1:-help}" in
        install)
            complete_installation
            ;;
        check)
            check_environment
            ;;
        deps)
            install_dependencies
            ;;
        build)
            build_docker_images
            ;;
        start)
            start_services
            ;;
        status)
            show_status
            ;;
        logs)
            show_logs
            ;;
        stop)
            stop_services
            ;;
        help|*)
            show_help
            ;;
    esac
}

# 执行主函数
main "$@"
