#!/bin/bash
# ========================================
#  OpenClaw 桌面启动脚本
#  开机启动时先执行 doctor --fix，再启动 Gateway
# ========================================

# 加载 shell 配置（确保 nvm、brew 等路径可用）
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" 2>/dev/null
[ -f "$HOME/.zshrc" ] && source "$HOME/.zshrc" 2>/dev/null
[ -f "$HOME/.bash_profile" ] && source "$HOME/.bash_profile" 2>/dev/null
[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" 2>/dev/null

# 检查 openclaw 是否可用
if ! command -v openclaw &> /dev/null; then
    echo ""
    echo "  [错误] 找不到 openclaw 命令！"
    echo ""
    echo "  解决方法："
    echo "  - 打开终端，输入: npm install -g openclaw@latest"
    echo "  - 然后重新运行此脚本"
    echo ""
    read -p "按回车键退出..."
    exit 1
fi

echo ""
echo "  ================================"
echo "    OpenClaw Gateway"
echo "  ================================"
echo ""

# 检查是否已在运行
if openclaw gateway status 2>/dev/null | grep -qiE "running|started|listening"; then
    echo "  状态: 已在运行"
    echo ""
    echo "  正在打开 Web UI..."
    open "http://127.0.0.1:18789/" 2>/dev/null || xdg-open "http://127.0.0.1:18789/" 2>/dev/null
    echo "  如果浏览器没有打开，请手动访问: http://127.0.0.1:18789/"
    sleep 2
    exit 0
fi

# 启动前执行 doctor --fix
echo "  [1/2] 执行 openclaw doctor --fix..."
openclaw doctor --fix
echo ""

# 启动 Gateway
echo "  [2/2] 启动 Gateway..."
openclaw gateway start

echo ""
echo "  启动完成！正在打开 Web UI..."
open "http://127.0.0.1:18789/" 2>/dev/null || xdg-open "http://127.0.0.1:18789/" 2>/dev/null
echo ""
echo "  Web UI: http://127.0.0.1:18789/"
echo "  按 Ctrl+C 停止 Gateway"
echo ""

wait
