#!/usr/bin/env bash
# 宿主机物理目录模式（Docker 不可用或 ./start.sh --host）
# shellcheck disable=SC1091

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"

REBUILD=0
NO_BROWSER=0
for arg in "$@"; do
  case "$arg" in
    --rebuild|-Rebuild) REBUILD=1 ;;
    --no-browser) NO_BROWSER=1 ;;
  esac
done

start_bg() {
  local name="$1" logfile="$2"
  shift 2
  local pidfile="$PID_DIR/$name.pid"
  if [[ -f "$pidfile" ]] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then
    c_warn "$name 已在运行 pid=$(cat "$pidfile")"
    return 0
  fi
  c_info "启动 $name"
  nohup "$@" >>"$logfile" 2>&1 &
  echo $! >"$pidfile"
  c_ok "$name pid=$(cat "$pidfile") 日志 $logfile"
}

ensure_postgres_running() {
  local pg_ctl=""
  pg_ctl="$(command -v pg_ctl 2>/dev/null || true)"
  if [[ -z "$pg_ctl" ]]; then
    for d in /usr/lib/postgresql/*/bin /usr/pgsql-*/bin; do
      [[ -x "$d/pg_ctl" ]] && pg_ctl="$d/pg_ctl" && break
    done
  fi
  if [[ -n "$pg_ctl" && -f "$PGDATA/PG_VERSION" ]]; then
    if ! "$pg_ctl" -D "$PGDATA" status >/dev/null 2>&1; then
      c_info "启动物理目录 Postgres → $PGDATA"
      mkdir -p "$RUNTIME/pg_sockets"
      "$pg_ctl" -D "$PGDATA" -l "$LOG_DIR/postgres.log" -o "-k $RUNTIME/pg_sockets" start
      sleep 1
    fi
  fi
}

c_warn "宿主机模式：数据落在 $RUNTIME"
if [[ ! -f "$RUNTIME/setup.ok" || "$REBUILD" -eq 1 ]]; then
  bash "$SCRIPT_DIR/setup-host.sh"
fi
# shellcheck source=/dev/null
[[ -f "$RUNTIME/env.sh" ]] && source "$RUNTIME/env.sh"

ensure_postgres_running

if [[ "$REBUILD" -eq 1 || ! -x "$ROOT/platform/platform" ]]; then
  (cd "$ROOT/platform" && go build -o platform .)
fi
if [[ "$REBUILD" -eq 1 || ! -x "$ROOT/gateway/gateway" ]]; then
  (cd "$ROOT/gateway" && go build -o gateway .)
fi

PY="$VENV_DIR/bin/python"
[[ -x "$PY" ]] || PY="$(command -v python3)"

start_bg platform "$LOG_DIR/platform.log" \
  bash -c "cd '$ROOT/platform' && exec ./platform -f etc/platform.yaml"
start_bg ai "$LOG_DIR/ai.log" \
  bash -c "cd '$ROOT/ai-service' && exec '$PY' -m uvicorn app:app --host 127.0.0.1 --port 8001"
start_bg gateway "$LOG_DIR/gateway.log" \
  bash -c "cd '$ROOT/gateway' && exec ./gateway -f etc/gateway.yaml"
start_bg web "$LOG_DIR/web.log" \
  bash -c "cd '$ROOT/web' && exec npm run dev -- --host 127.0.0.1 --port 5173"

wait_port 8888 platform 45 || true
wait_http "http://127.0.0.1:8001/health" ai-service 45 || true
wait_http "http://127.0.0.1:8180/gateway/health" gateway 45 || true
wait_port 5173 web 60 || true

cat <<EOF

========================================
  前端    http://127.0.0.1:5173
  网关    http://127.0.0.1:8180
  账号    demo / demo123
  模式    宿主机物理目录
  停止    ./stop.sh
========================================

EOF

if [[ "$NO_BROWSER" -eq 0 ]] && have_cmd xdg-open; then
  xdg-open "http://127.0.0.1:5173" >/dev/null 2>&1 || true
fi
