#!/bin/bash

# Browser-Use MCP服务启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

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

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SERVICE_DIR="$PROJECT_ROOT/mcp-services/browser-use-mcp"

log_info "启动Browser-Use MCP服务..."

# 检查服务目录
if [[ ! -d "$SERVICE_DIR" ]]; then
    log_error "服务目录不存在: $SERVICE_DIR"
    exit 1
fi

cd "$SERVICE_DIR"

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    log_error "Python3 未安装"
    exit 1
fi

# 检查虚拟环境
if [[ ! -d "venv" ]]; then
    log_info "创建虚拟环境..."
    python3 -m venv venv
fi

# 激活虚拟环境
source venv/bin/activate

# 安装依赖
log_info "安装依赖..."
pip install -r requirements.txt

# 检查环境变量
if [[ -z "$OPENAI_API_KEY" && -z "$ANTHROPIC_API_KEY" ]]; then
    log_warning "未设置AI API密钥，某些功能可能无法使用"
    log_warning "请设置 OPENAI_API_KEY 或 ANTHROPIC_API_KEY 环境变量"
fi

# 安装Playwright浏览器
log_info "安装Playwright浏览器..."
playwright install chromium

# 创建必要的目录
mkdir -p logs screenshots recordings

# 检查端口是否被占用
PORT=9029
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then
    log_warning "端口 $PORT 已被占用，尝试停止现有服务..."
    pkill -f "browser-use-mcp" || true
    sleep 2
fi

# 启动服务
log_info "启动Browser-Use MCP服务 (端口: $PORT)..."

# 设置环境变量
export PYTHONPATH="$SERVICE_DIR:$PYTHONPATH"
export BROWSER_HEADLESS=true
export LOG_LEVEL=INFO

# 启动服务
python3 main.py &
SERVICE_PID=$!

# 等待服务启动
sleep 5

# 检查服务是否启动成功
if kill -0 $SERVICE_PID 2>/dev/null; then
    log_success "Browser-Use MCP服务启动成功 (PID: $SERVICE_PID)"
    
    # 健康检查
    if curl -s "http://localhost:$PORT/health" > /dev/null; then
        log_success "服务健康检查通过"
    else
        log_warning "服务健康检查失败，但进程仍在运行"
    fi
    
    # 保存PID
    echo $SERVICE_PID > "$SERVICE_DIR/service.pid"
    
    log_info "服务访问地址: http://localhost:$PORT"
    log_info "API文档: http://localhost:$PORT/docs"
    log_info "日志文件: $SERVICE_DIR/logs/browser-use-mcp.log"
    
else
    log_error "Browser-Use MCP服务启动失败"
    exit 1
fi
