#!/bin/bash
# ============================================================
#  DeepSeek Harness (DSH) 一键启动脚本
#  ----------------------------------------------------------
#  用法:
#    ~/start-dsh.sh           前台启动（推荐：终端窗口里能看到日志，Ctrl+C 停止）
#    ~/start-dsh.sh -d        后台启动（窗口可关，日志写入 ~/.dsh/web.log）
#    ~/start-dsh.sh stop      停止正在运行的 DSH
#    ~/start-dsh.sh status    查看运行状态
#
#  如果 DSH 已在运行，直接打开浏览器，不会重复启动。
# ============================================================

set -u

# 从 Finder/App 环境启动时 PATH 可能不含 homebrew，兜底补上
export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$PATH"

PORT="${DSH_PORT:-3080}"
URL="http://127.0.0.1:${PORT}"
LOG="$HOME/.dsh/web.log"

is_running() {
  curl -fsS -o /dev/null --max-time 2 "$URL" 2>/dev/null
}

cmd="${1:-}"

case "$cmd" in
  stop)
    PID=$(lsof -ti tcp:"$PORT" -sTCP:LISTEN 2>/dev/null | head -1)
    if [ -n "$PID" ]; then
      kill "$PID" && echo "已停止 DSH (PID $PID)" || echo "停止失败"
    else
      echo "DSH 当前未在运行"
    fi
    exit 0
    ;;
  status)
    if is_running; then
      echo "DSH 正在运行 → $URL"
    else
      echo "DSH 未运行"
    fi
    exit 0
    ;;
  --build-app)
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    exec bash "$SCRIPT_DIR/build-dsh-app.sh"
    ;;
esac

# 已在运行 → 直接开浏览器
if is_running; then
  echo "DSH 已在运行，直接打开 $URL"
  open "$URL"
  exit 0
fi

# 后台启动模式
if [ "$cmd" = "-d" ]; then
  echo "后台启动 DSH…（日志: $LOG）"
  nohup dsh web --port "$PORT" >>"$LOG" 2>&1 &
  for _ in $(seq 1 90); do
    if is_running; then
      echo "启动完成 → $URL"
      open "$URL"
      exit 0
    fi
    sleep 1
  done
  echo "90 秒内未就绪，请查看日志: $LOG"
  exit 1
fi

# 前台启动模式：dsh 跑在前台（Ctrl+C 可停止），
# 后台轮询端口就绪后自动打开浏览器。
(
  for _ in $(seq 1 90); do
    if is_running; then
      open "$URL"
      exit 0
    fi
    sleep 1
  done
) &
POLLER=$!
trap 'kill "$POLLER" 2>/dev/null' INT TERM EXIT

echo "正在启动 DeepSeek Harness → $URL （Ctrl+C 停止）"
dsh web --port "$PORT"
