#!/usr/bin/env bash
# 一键启动 US-Iran 态势面板：API + 前端 + 爬虫服务
set -e
# 使用 UTF-8，便于终端输入/显示中文
export LANG="${LANG:-en_US.UTF-8}"
export LC_ALL="${LC_ALL:-en_US.UTF-8}"
cd "$(dirname "$0")"

# 若存在 .env 则加载（可在此设置 DASHSCOPE_API_KEY=sk-xxx，勿提交 .env）
[ -f .env ] && set -a && . ./.env && set +a

# 面板实时数据：1=仅用规则提取战损/据点（无需 Ollama），0=用 Ollama/通义。有 DASHSCOPE_API_KEY 时自动用通义
export CLEANER_AI_DISABLED=1
export PARSER_AI_DISABLED=0
# GDELT 国内常超时，仅用 RSS 更新（如需 GDELT 可改为 0）
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)..."
# 若指定了 DB_PATH，则以 DB_PATH 为准；否则默认使用 server/data.db
DB_FILE_PATH="${DB_PATH:-server/data.db}"
if [ ! -f "$DB_FILE_PATH" ]; then
  echo "  - DB file not found at $DB_FILE_PATH, running api:seed once"
  npm run api:seed
else
  echo "  - Existing DB detected at $DB_FILE_PATH, skip seeding"
  echo "    (若刚更新了 seed 想刷新地图/战损等，请先执行: npm run api:seed)"
fi

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
