#!/bin/bash
# PolyMind 桌面启动器：确保服务运行后，用默认浏览器打开前端。
set -u
URL="${POLYMIND_URL:-http://localhost:3000}"
SERVICES="witty-backend.service polymind.service nginx.service"

# 1) 服务已在镜像中 enable（开机自启），这里仅兜底启动
if command -v systemctl >/dev/null 2>&1; then
    for svc in $SERVICES; do
        systemctl is-active --quiet "$svc" 2>/dev/null || systemctl start "$svc" 2>/dev/null || true
    done
fi

# 2) 等待健康检查就绪 (nginx 配置里有 /health 返回 200 OK)
if command -v curl >/dev/null 2>&1; then
    for _ in $(seq 1 15); do
        curl -fsS --max-time 2 "http://127.0.0.1:3000/health" >/dev/null 2>&1 && break
        sleep 1
    done
fi

# 3) 用默认浏览器打开（联动浏览器）
open_browser() {
    if command -v xdg-open >/dev/null 2>&1; then
        xdg-open "$1" >/dev/null 2>&1 && return 0
    fi
    if command -v gio >/dev/null 2>&1; then
        gio open "$1" >/dev/null 2>&1 && return 0
    fi
    return 1
}
if ! open_browser "$URL"; then
    echo "PolyMind 已启动，请在浏览器打开: $URL"
fi
exit 0
