#!/usr/bin/env bash
# 一键启动 US-Iran 态势面板：API + 前端 + 爬虫服务
set -e
cd "$(dirname "$0")"

# 无 Ollama 时禁用 AI；GDELT 国内常超时，仅用 RSS 更新
export CLEANER_AI_DISABLED=1
export PARSER_AI_DISABLED=1
export GDELT_DISABLED=1
export RSS_INTERVAL_SEC=60

echo "==> Checking dependencies..."
[ ! -d node_modules ] && npm install

echo "==> Checking crawler Python deps..."
pip install -q -r crawler/requirements.txt 2>/dev/null || true

echo "==> Seeding database (if needed)..."
[ ! -f server/data.db ] && npm run api:seed

echo "==> Starting API (http://localhost:3001)..."
npm run api &
API_PID=$!

# 等待 API 就绪后再启动爬虫
sleep 2

echo "==> Starting GDELT/RSS crawler (http://localhost:8000)..."
npm run gdelt &
GDELT_PID=$!

echo "==> Starting frontend (Vite dev server)..."
npm run dev &
DEV_PID=$!

cleanup() {
  echo ""
  echo "==> Shutting down..."
  kill $API_PID $GDELT_PID $DEV_PID 2>/dev/null || true
  exit 0
}
trap cleanup SIGINT SIGTERM

echo ""
echo "==> All services running. Frontend: http://localhost:5173  |  API: http://localhost:3001"
echo "    Press Ctrl+C to stop all."
echo ""
wait
