#!/bin/bash
# ==============================================================================
# Gemini 集控系统 - macOS 原生启动引导程序 (支持内置独立便携环境与沙箱自愈)
# ==============================================================================

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../Resources" >/dev/null 2>&1 && pwd )"
cd "$DIR"

# 1. 优先级一：检测是否内置了独立的便携式 Python 运行环境 (完全离线模式，零依赖)
RUN_PY=""
if [ -x "$DIR/runtime/bin/python3" ]; then
    RUN_PY="$DIR/runtime/bin/python3"
    export PYTHONHOME="$DIR/runtime"
    export PYTHONPATH="$DIR/runtime/lib/python3.11/site-packages:$DIR:$PYTHONPATH"
    export PATH="$DIR/runtime/bin:$PATH"
elif [ -x "$DIR/runtime/python3" ]; then
    RUN_PY="$DIR/runtime/python3"
    export PYTHONHOME="$DIR/runtime"
    export PYTHONPATH="$DIR/runtime/lib/python3.11/site-packages:$DIR:$PYTHONPATH"
    export PATH="$DIR/runtime:$PATH"
fi

# 2. 优先级二：若未内置便携运行时，自动查找系统 Python 并通过隔离虚拟环境 (~/.mysuperhub/venv) 运行
if [ -z "$RUN_PY" ]; then
    find_python() {
        for cand in \
            "/opt/homebrew/bin/python3" \
            "/usr/local/bin/python3" \
            "/usr/bin/python3" \
            "$(which python3 2>/dev/null)"; do
            if [ -x "$cand" ]; then
                echo "$cand"
                return 0
            fi
        done
        return 1
    }

    SYS_PY=$(find_python)

    if [ -z "$SYS_PY" ]; then
        osascript -e 'display alert "未检测到 Python 3 环境" message "当前交付包未内嵌便携 Python，需要系统环境提供 Python 3。\n\n请在终端中运行：brew install python\n或前往官网下载：https://www.python.org/" as critical'
        exit 1
    fi

    check_py_deps() {
        "$1" -c "import fastapi, uvicorn, pydantic, PIL, psutil, websocket, websockets, requests, av, cryptography" >/dev/null 2>&1
        return $?
    }

    VENV_DIR="$HOME/.mysuperhub/venv"
    VENV_PY="$VENV_DIR/bin/python3"

    if check_py_deps "$SYS_PY"; then
        RUN_PY="$SYS_PY"
    elif [ -x "$VENV_PY" ] && check_py_deps "$VENV_PY"; then
        RUN_PY="$VENV_PY"
    else
        osascript -e 'display notification "正在为您初始化独立沙箱依赖环境，请稍候..." with title "Gemini 集控中心" subtitle "环境配置中"'
        mkdir -p "$HOME/.mysuperhub"
        if [ ! -d "$VENV_DIR" ]; then
            "$SYS_PY" -m venv "$VENV_DIR" >/dev/null 2>&1
        fi
        if [ -x "$VENV_DIR/bin/pip" ]; then
            "$VENV_DIR/bin/pip" install --quiet -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt >/dev/null 2>&1 || \
            "$VENV_DIR/bin/pip" install --quiet -r requirements.txt >/dev/null 2>&1
        fi
        if check_py_deps "$VENV_PY"; then
            RUN_PY="$VENV_PY"
        else
            osascript -e 'display alert "缺少必要的 Python 运行依赖" message "自动配置未成功，请双击运行安装包内的【一键配置mac运行环境.command】或在终端手动执行 pip3 install -r requirements.txt" as critical'
            exit 1
        fi
    fi
fi

# 3. 检测是否安装了 Chrome / Edge 浏览器
has_chrome=0
for c_cand in \
    "/Applications/Google Chrome.app" \
    "$HOME/Applications/Google Chrome.app" \
    "/Applications/Microsoft Edge.app" \
    "$HOME/Applications/Microsoft Edge.app" \
    "/Applications/Brave Browser.app" \
    "/Applications/Chromium.app"; do
    if [ -d "$c_cand" ]; then
        has_chrome=1
        break
    fi
done

if [ $has_chrome -eq 0 ]; then
    osascript -e 'display alert "提示：未检测到 Google Chrome 浏览器" message "Gemini 集控系统需要基于 Chrome/Edge 运行自动化工作节点。\n\n建议前往官方下载安装 Chrome：https://www.google.com/chrome/\n\n（未安装前您仍可查看控制台，但无法打开登录节点）" as warning' >/dev/null 2>&1 &
fi

# 4. 避免端口冲突：如果 8765 已被旧的集控占用，先执行平滑关闭
"$RUN_PY" bridge_server/start_worker_chrome.py --stop-all >/dev/null 2>&1

# 5. 在后台启动主控服务端 (Port 8765)
LOG_FILE="/tmp/gemini_cluster.log"
nohup "$RUN_PY" -X utf8 bridge_server/server.py > "$LOG_FILE" 2>&1 &
SERVER_PID=$!

# 6. 轮询等待服务端完全就绪 (最长等待 12 秒)
WAIT_SECS=0
while [ $WAIT_SECS -lt 12 ]; do
    if curl -s "http://127.0.0.1:8765/api/cluster/accounts" >/dev/null 2>&1; then
        break
    fi
    sleep 0.8
    WAIT_SECS=$((WAIT_SECS + 1))
done

# 7. 服务就绪：弹出默认浏览器打开控制台 UI 并发出系统通知
if curl -s "http://127.0.0.1:8765/api/cluster/accounts" >/dev/null 2>&1; then
    open "http://127.0.0.1:8765/"
    osascript -e 'display notification "集控中心已成功启动！\n控制台地址: http://127.0.0.1:8765" with title "Gemini 集控中心" subtitle "运行中"'
else
    open "http://127.0.0.1:8765/"
fi

exit 0
