#!/bin/bash

# ================= 配置区域 =================
DEBUG_PORT=9222
CHROME_PATH=""
USER_DATA_DIR=""
OS_TYPE=$(uname -s)

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

echo -e "${GREEN}[INFO]${NC} 正在检测系统环境..."

# ================= 1. 路径探测逻辑 =================
if [ "$OS_TYPE" == "Darwin" ]; then
    # --- macOS ---
    echo -e "${GREEN}🍎${NC} 检测到 macOS"
    USER_DATA_DIR="$HOME/Library/Application Support/ChromeAutoProfile"

    PATHS=(
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        "$HOME/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"
    )

    for p in "${PATHS[@]}"; do
        if [ -f "$p" ]; then
            CHROME_PATH="$p"
            break
        fi
    done

elif [ "$OS_TYPE" == "Linux" ]; then
    # --- Linux ---
    echo -e "${GREEN}🐧${NC} 检测到 Linux"
    USER_DATA_DIR="$HOME/.config/chrome-automation-profile"

    if command -v google-chrome &> /dev/null; then
        CHROME_PATH="google-chrome"
    elif command -v chromium-browser &> /dev/null; then
        CHROME_PATH="chromium-browser"
    elif command -v chromium &> /dev/null; then
        CHROME_PATH="chromium"
    elif [ -f "/usr/bin/google-chrome" ]; then
        CHROME_PATH="/usr/bin/google-chrome"
    elif [ -f "/usr/bin/chromium" ]; then
        CHROME_PATH="/usr/bin/chromium"
    elif [ -f "/snap/bin/chromium" ]; then
        CHROME_PATH="/snap/bin/chromium"
    fi
else
    echo -e "${RED}❌${NC} 不支持的操作系统: $OS_TYPE"
    exit 1
fi

# ================= 2. 验证浏览器路径 =================
if [ -z "$CHROME_PATH" ]; then
    echo -e "${RED}❌${NC} 错误：未找到 Google Chrome 或 Chromium。"
    echo "请安装浏览器或检查 PATH 环境变量。"
    exit 1
fi

echo -e "${GREEN}✅${NC} 找到浏览器: $CHROME_PATH"
echo -e "${GREEN}📂${NC} 数据目录: $USER_DATA_DIR"

# 创建数据目录 (mkdir -p 会自动处理父目录)
mkdir -p "$USER_DATA_DIR"

# ================= 3. 检查端口是否占用 =================
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:$DEBUG_PORT/json/version" | grep -q "200"; then
    echo -e "${GREEN}✅${NC} 浏览器似乎已经在运行 (端口 $DEBUG_PORT 已响应)。"
    echo -e "${YELLOW}💡${NC} 无需重复启动，可直接运行 Python 脚本。"
    exit 0
fi

echo -e "${YELLOW}🚀${NC} 正在启动浏览器..."

CMD_ARGS=(
    "--remote-debugging-port=$DEBUG_PORT"
    "--user-data-dir=$USER_DATA_DIR"  # 数组元素会自动处理内部空格，不需要手动加引号
    "--no-first-run"
    "--no-default-browser-check"
    "--disable-gpu" # 增加稳定性
)

# Linux Root 用户特殊处理
if [ "$OS_TYPE" == "Linux" ] && [ "$EUID" -eq 0 ]; then
    echo -e "${YELLOW}⚠️${NC} 检测到 Root 用户，添加 --no-sandbox"
    CMD_ARGS+=("--no-sandbox" "--disable-setuid-sandbox")
fi

# 打印最终执行的命令供调试 (将数组展开为字符串显示)
echo -e "${YELLOW}[DEBUG]${NC} 执行命令: $CHROME_PATH ${CMD_ARGS[*]}"

# ================= 5. 后台启动 =================
nohup "$CHROME_PATH" "${CMD_ARGS[@]}" > /tmp/chrome_debug.log 2>&1 &

PID=$!
echo -e "${YELLOW}⏳${NC} 等待浏览器启动 (5 秒)... (PID: $PID)"
sleep 5

# ================= 6. 验证启动结果 =================
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:$DEBUG_PORT/json/version" | grep -q "200"; then
    echo -e "${GREEN}✅${NC} 成功！浏览器已启动。"
    echo -e "${GREEN}📄${NC} 日志文件: /tmp/chrome_debug.log"
else
    echo -e "${RED}❌${NC} 启动失败！无法连接到端口 $DEBUG_PORT。"
    echo -e "${RED}📄${NC} 最后 20 行日志:"
    echo "----------------------------------------"
    tail -n 20 /tmp/chrome_debug.log
    echo "----------------------------------------"
    echo ""
    echo -e "${YELLOW}💡 建议:${NC}"
    echo "1. 检查是否有旧的 Chrome 进程卡死 (killall 'Google Chrome')"
    echo "2. 尝试删除数据目录后重试: rm -rf '$USER_DATA_DIR'"
    echo "3. 如果是 Linux，确保安装了依赖库 (如 libgbm1 等)"
    exit 1
fi