#!/bin/bash
# 🔗 WhatsApp Bridge MCP 本地安装脚本 (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 本地安装器"
    print_color "CYAN" "================================================"
    print_color "GREEN" "本地环境安装 WhatsApp Bridge MCP"
    echo ""
}

# 检查并安装Go环境
install_go() {
    print_color "YELLOW" "🔍 检查Go环境..."
    
    if command -v go &> /dev/null; then
        local go_version=$(go version)
        print_color "GREEN" "✅ Go已安装: $go_version"
        return 0
    fi
    
    print_color "YELLOW" "📦 Go未安装，开始安装..."
    
    # 检查是否有Homebrew
    if command -v brew &> /dev/null; then
        print_color "BLUE" "使用Homebrew安装Go..."
        brew install go
    else
        print_color "YELLOW" "Homebrew未安装，请手动安装Go:"
        print_color "NC" "1. 访问 https://golang.org/dl/"
        print_color "NC" "2. 下载macOS版本的Go安装包"
        print_color "NC" "3. 安装后重新运行此脚本"
        exit 1
    fi
    
    # 验证安装
    if command -v go &> /dev/null; then
        local go_version=$(go version)
        print_color "GREEN" "✅ Go安装成功: $go_version"
    else
        print_color "RED" "❌ Go安装失败"
        exit 1
    fi
}

# 构建WhatsApp Bridge
build_whatsapp_bridge() {
    print_color "YELLOW" "🔨 构建WhatsApp Bridge..."
    
    cd whatsapp-bridge
    
    # 设置Go环境变量
    export CGO_ENABLED=1
    export GOOS=darwin
    export GOARCH=amd64
    
    print_color "BLUE" "📥 下载Go依赖..."
    go mod download
    
    print_color "BLUE" "🔨 编译WhatsApp Bridge..."
    go build -o whatsapp-bridge main.go
    
    if [ -f "whatsapp-bridge" ]; then
        print_color "GREEN" "✅ WhatsApp Bridge构建成功"
    else
        print_color "RED" "❌ WhatsApp Bridge构建失败"
        exit 1
    fi
    
    cd ..
}

# 设置Python MCP Server
setup_mcp_server() {
    print_color "YELLOW" "🐍 设置Python MCP Server..."
    
    cd whatsapp-mcp-server
    
    print_color "BLUE" "📦 安装Python依赖..."
    uv sync
    
    print_color "GREEN" "✅ Python MCP Server设置完成"
    cd ..
}

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

# 启动WhatsApp Bridge (后台运行)
echo "启动WhatsApp Bridge..."
cd whatsapp-bridge
mkdir -p store logs
nohup ./whatsapp-bridge > logs/bridge.log 2>&1 &
BRIDGE_PID=$!
echo "WhatsApp Bridge PID: $BRIDGE_PID"
cd ..

# 等待Bridge启动
echo "等待WhatsApp Bridge启动..."
sleep 5

# 检查Bridge是否启动成功
if curl -f http://localhost:8080/health &> /dev/null; then
    echo "✅ WhatsApp Bridge启动成功"
else
    echo "⚠️ WhatsApp Bridge可能还在启动中..."
fi

# 启动MCP Server
echo "启动MCP Server..."
cd whatsapp-mcp-server
export BRIDGE_HOST=localhost
export BRIDGE_PORT=8080
export MCP_PORT=9023
uv run main.py
EOF
    
    # 停止脚本
    cat > stop-whatsapp-mcp.sh << 'EOF'
#!/bin/bash
echo "🛑 停止WhatsApp MCP服务..."

# 停止所有相关进程
pkill -f "whatsapp-bridge"
pkill -f "main.py"

echo "✅ WhatsApp MCP服务已停止"
EOF
    
    # 添加执行权限
    chmod +x start-whatsapp-bridge.sh
    chmod +x start-mcp-server.sh
    chmod +x start-whatsapp-mcp.sh
    chmod +x stop-whatsapp-mcp.sh
    
    print_color "GREEN" "✅ 启动脚本创建完成"
}

# 创建Claude Desktop配置
create_claude_config() {
    print_color "YELLOW" "⚙️ 创建Claude Desktop配置..."
    
    local config_dir=""
    if [[ "$OSTYPE" == "darwin"* ]]; then
        config_dir="$HOME/Library/Application Support/Claude"
    else
        config_dir="$HOME/.config/claude"
    fi
    
    mkdir -p "$config_dir"
    
    cat > "$config_dir/claude_desktop_config.json" << 'EOF'
{
  "mcpServers": {
    "whatsapp": {
      "command": "uv",
      "args": [
        "--directory",
        "/Users/USERNAME_ENCRYPTED/Desktop/小红书投放/whatsapp-mcp/whatsapp-mcp-server",
        "run",
        "main.py"
      ],
      "env": {
        "BRIDGE_HOST": "localhost",
        "BRIDGE_PORT": "8080",
        "MCP_PORT": "9023"
      }
    }
  }
}
EOF
    
    print_color "GREEN" "✅ Claude Desktop配置已创建: $config_dir/claude_desktop_config.json"
    print_color "YELLOW" "请重启Claude Desktop应用以加载新配置"
}

# 显示使用说明
show_usage() {
    print_color "CYAN" "📖 使用说明:"
    echo ""
    print_color "YELLOW" "启动服务:"
    print_color "NC" "  ./start-whatsapp-mcp.sh     # 启动完整服务"
    print_color "NC" "  ./start-whatsapp-bridge.sh  # 仅启动WhatsApp Bridge"
    print_color "NC" "  ./start-mcp-server.sh       # 仅启动MCP Server"
    echo ""
    print_color "YELLOW" "停止服务:"
    print_color "NC" "  ./stop-whatsapp-mcp.sh      # 停止所有服务"
    echo ""
    print_color "YELLOW" "首次使用:"
    print_color "NC" "1. 运行 ./start-whatsapp-bridge.sh"
    print_color "NC" "2. 扫描终端中显示的QR码"
    print_color "NC" "3. 在另一个终端运行 ./start-mcp-server.sh"
    print_color "NC" "4. 重启Claude Desktop"
    echo ""
    print_color "YELLOW" "服务地址:"
    print_color "NC" "  WhatsApp Bridge: http://localhost:8080"
    print_color "NC" "  MCP Server: localhost:9023"
}

# 完整安装流程
complete_installation() {
    print_color "GREEN" "🚀 开始本地安装流程..."
    
    # 1. 安装Go环境
    install_go
    
    # 2. 构建WhatsApp Bridge
    build_whatsapp_bridge
    
    # 3. 设置Python MCP Server
    setup_mcp_server
    
    # 4. 创建启动脚本
    create_start_scripts
    
    # 5. 创建Claude Desktop配置
    create_claude_config
    
    print_color "GREEN" "🎉 WhatsApp MCP本地安装完成！"
    echo ""
    show_usage
}

# 主函数
main() {
    print_header
    
    case "${1:-install}" in
        install)
            complete_installation
            ;;
        go)
            install_go
            ;;
        build)
            build_whatsapp_bridge
            ;;
        python)
            setup_mcp_server
            ;;
        scripts)
            create_start_scripts
            ;;
        config)
            create_claude_config
            ;;
        help|*)
            show_usage
            ;;
    esac
}

# 执行主函数
main "$@"
