#!/usr/bin/env bash
set -e
ROOT="$(cd "$(dirname "$0")" && pwd)"

ensure_backend_venv() {
  cd "$ROOT/backend"
  if [ ! -d venv ]; then
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt -q
  else
    source venv/bin/activate
  fi
}

run_backend() {
  ensure_backend_venv
  exec uvicorn main:app --reload --host 0.0.0.0 --port 18004
}

run_frontend() {
  cd "$ROOT/frontend"
  [ -d node_modules ] || npm install
  exec npm run dev -- --host 0.0.0.0 --port 18003
}

run_all() {
  ensure_backend_venv
  cd "$ROOT/frontend"
  [ -d node_modules ] || npm install

  trap 'kill $(jobs -p) 2>/dev/null' EXIT INT TERM

  echo "启动后端 http://localhost:18004 (API 文档 /docs)"
  (cd "$ROOT/backend" && source venv/bin/activate && uvicorn main:app --reload --host 0.0.0.0 --port 18004) &

  echo "启动前端 http://localhost:18003"
  (cd "$ROOT/frontend" && npm run dev -- --host 0.0.0.0 --port 18003) &

  echo "按 Ctrl+C 停止前后端"
  wait
}

case "${1:-all}" in
  backend) run_backend ;;
  frontend) run_frontend ;;
  all) run_all ;;
  *)
    echo "用法: ./start.sh [all|backend|frontend]"
    echo ""
    echo "  ./start.sh          # 同一终端同时启动前后端"
    echo "  ./start.sh all      # 同上"
    echo "  ./start.sh backend  # 仅后端 (需另开终端跑 frontend)"
    echo "  ./start.sh frontend # 仅前端"
    echo ""
    echo "或按 README 在两个终端分别执行 backend / frontend 下的命令。"
    exit 1
    ;;
esac
