#!/bin/bash
# 🚀 WhatsApp MCP 快速安装脚本

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'

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

print_header() {
    clear
    print_color "CYAN" "🚀 WhatsApp MCP 快速安装器"
    print_color "CYAN" "================================"
    print_color "GREEN" "自动安装 Go + WhatsApp Bridge MCP"
    echo ""
}

# 安装Homebrew
install_homebrew() {
    if command -v brew &> /dev/null; then
        print_color "GREEN" "✅ Homebrew已安装"
        return 0
    fi
    
    print_color "YELLOW" "📦 安装Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    
    # 添加到PATH
    echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
    eval "$(/opt/homebrew/bin/brew shellenv)"
    
    print_color "GREEN" "✅ Homebrew安装完成"
}

# 安装Go
install_go() {
    if command -v go &> /dev/null; then
        print_color "GREEN" "✅ Go已安装: $(go version)"
        return 0
    fi
    
    print_color "YELLOW" "📦 安装Go..."
    brew install go
    
    print_color "GREEN" "✅ Go安装完成: $(go version)"
}

# 构建项目
build_project() {
    print_color "YELLOW" "🔨 构建WhatsApp Bridge..."
    
    cd whatsapp-mcp/whatsapp-bridge
    
    # 设置环境变量
    export CGO_ENABLED=1
    export GOOS=darwin
    export GOARCH=amd64
    
    # 下载依赖
    print_color "BLUE" "📥 下载Go依赖..."
    go mod download
    
    # 构建
    print_color "BLUE" "🔨 编译项目..."
    go build -o whatsapp-bridge main.go
    
    # 创建目录
    mkdir -p store logs
    
    cd ../..
    print_color "GREEN" "✅ WhatsApp Bridge构建完成"
}

# 设置Python环境
setup_python() {
    print_color "YELLOW" "🐍 设置Python环境..."
    
    cd whatsapp-mcp/whatsapp-mcp-server
    
    # 安装依赖
    print_color "BLUE" "📦 安装Python依赖..."
    uv sync
    
    # 创建目录
    mkdir -p logs
    
    cd ../..
    print_color "GREEN" "✅ Python环境设置完成"
}

# 创建启动脚本
create_scripts() {
    print_color "YELLOW" "📝 创建启动脚本..."
    
    # Bridge启动脚本
    cat > start-bridge.sh << 'EOF'
#!/bin/bash
echo "🚀 启动WhatsApp Bridge..."
cd whatsapp-mcp/whatsapp-bridge
./whatsapp-bridge
EOF
    
    # MCP启动脚本
    cat > start-mcp.sh << 'EOF'
#!/bin/bash
echo "🚀 启动WhatsApp MCP Server..."
cd whatsapp-mcp/whatsapp-mcp-server
export BRIDGE_HOST=localhost
export BRIDGE_PORT=8080
export MCP_PORT=9023
uv run main.py
EOF
    
    # 完整启动脚本
    cat > start-whatsapp.sh << 'EOF'
#!/bin/bash
echo "🚀 启动WhatsApp MCP完整服务..."

# 检查Bridge是否已运行
if pgrep -f "whatsapp-bridge" > /dev/null; then
    echo "WhatsApp Bridge已在运行"
else
    echo "启动WhatsApp Bridge..."
    cd whatsapp-mcp/whatsapp-bridge
    nohup ./whatsapp-bridge > logs/bridge.log 2>&1 &
    echo "WhatsApp Bridge已启动 (PID: $!)"
    cd ../..
    sleep 3
fi

# 检查MCP Server是否已运行
if pgrep -f "main.py" > /dev/null; then
    echo "MCP Server已在运行"
else
    echo "启动MCP Server..."
    cd whatsapp-mcp/whatsapp-mcp-server
    export BRIDGE_HOST=localhost
    export BRIDGE_PORT=8080
    export MCP_PORT=9023
    uv run main.py
fi
EOF
    
    # 停止脚本
    cat > stop-whatsapp.sh << 'EOF'
#!/bin/bash
echo "🛑 停止WhatsApp MCP服务..."
pkill -f "whatsapp-bridge"
pkill -f "main.py"
echo "✅ 服务已停止"
EOF
    
    # 状态检查脚本
    cat > status-whatsapp.sh << 'EOF'
#!/bin/bash
echo "📊 WhatsApp MCP服务状态:"
echo ""

# 检查Bridge
if pgrep -f "whatsapp-bridge" > /dev/null; then
    echo "✅ WhatsApp Bridge: 运行中"
    if curl -f http://localhost:8080/health &> /dev/null; then
        echo "✅ Bridge健康检查: 通过"
    else
        echo "⚠️ Bridge健康检查: 失败"
    fi
else
    echo "❌ WhatsApp Bridge: 未运行"
fi

# 检查MCP Server
if pgrep -f "main.py" > /dev/null; then
    echo "✅ MCP Server: 运行中"
    if nc -z localhost 9023 &> /dev/null; then
        echo "✅ MCP端口检查: 通过"
    else
        echo "⚠️ MCP端口检查: 失败"
    fi
else
    echo "❌ MCP Server: 未运行"
fi

echo ""
echo "📈 进程信息:"
ps aux | grep -E "(whatsapp-bridge|main.py)" | grep -v grep
EOF
    
    # 添加执行权限
    chmod +x start-bridge.sh start-mcp.sh start-whatsapp.sh stop-whatsapp.sh status-whatsapp.sh
    
    print_color "GREEN" "✅ 启动脚本创建完成"
}

# 配置Claude Desktop
configure_claude() {
    print_color "YELLOW" "⚙️ 配置Claude Desktop..."
    
    local config_dir="$HOME/Library/Application Support/Claude"
    mkdir -p "$config_dir"
    
    local current_dir=$(pwd)
    
    cat > "$config_dir/claude_desktop_config.json" << EOF
{
  "mcpServers": {
    "whatsapp": {
      "command": "uv",
      "args": [
        "--directory",
        "$current_dir/whatsapp-mcp/whatsapp-mcp-server",
        "run",
        "main.py"
      ],
      "env": {
        "BRIDGE_HOST": "localhost",
        "BRIDGE_PORT": "8080",
        "MCP_PORT": "9023"
      }
    }
  }
}
EOF
    
    print_color "GREEN" "✅ Claude Desktop配置完成"
    print_color "YELLOW" "请重启Claude Desktop应用"
}

# 显示完成信息
show_completion() {
    print_color "GREEN" "🎉 WhatsApp MCP安装完成！"
    echo ""
    print_color "CYAN" "📱 使用步骤:"
    print_color "NC" "1. 启动服务: ./start-whatsapp.sh"
    print_color "NC" "2. 扫描QR码完成WhatsApp认证"
    print_color "NC" "3. 重启Claude Desktop"
    print_color "NC" "4. 在Claude中测试WhatsApp功能"
    echo ""
    print_color "CYAN" "🔧 管理命令:"
    print_color "NC" "  ./start-whatsapp.sh   # 启动服务"
    print_color "NC" "  ./stop-whatsapp.sh    # 停止服务"
    print_color "NC" "  ./status-whatsapp.sh  # 查看状态"
    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认证"
}

# 主安装流程
main() {
    print_header
    
    print_color "BLUE" "开始安装流程..."
    echo ""
    
    # 1. 安装Homebrew
    install_homebrew
    
    # 2. 安装Go
    install_go
    
    # 3. 构建项目
    build_project
    
    # 4. 设置Python环境
    setup_python
    
    # 5. 创建启动脚本
    create_scripts
    
    # 6. 配置Claude Desktop
    configure_claude
    
    # 7. 显示完成信息
    show_completion
}

# 错误处理
trap 'print_color "RED" "❌ 安装过程中出现错误，请检查上面的错误信息"' ERR

# 执行主函数
main "$@"
