#!/usr/bin/env bash
# 检查攻击地点/打击线是否完整（与 seed.js 一致）
# 用法: DB_PATH=server/data.db ./scripts/check-attack-locations.sh
# 裸机: cd /root/usa && ./scripts/check-attack-locations.sh

set -e
PROJECT_ROOT="${PROJECT_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
DB_PATH="${DB_PATH:-$PROJECT_ROOT/server/data.db}"

echo "=========================================="
echo "攻击地点 / 打击线 检查"
echo "DB: $DB_PATH"
echo "=========================================="

if [[ ! -f "$DB_PATH" ]]; then
  echo "错误: 数据库文件不存在"
  exit 1
fi

if ! command -v sqlite3 &>/dev/null; then
  echo "需要 sqlite3。安装: yum install sqlite 或 apt install sqlite3"
  exit 1
fi

# 期望数量（与 server/seed.js 一致）
EXPECT_US=62    # getUsLocations: naval + attacked + newBases
EXPECT_IRAN=18  # iranLocs 条数
EXPECT_ISRAEL=4
EXPECT_LINCOLN=5
EXPECT_FORD=7

n_us=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM key_location WHERE side='us';" 2>/dev/null || echo "0")
n_iran=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM key_location WHERE side='iran';" 2>/dev/null || echo "0")
n_israel=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM map_strike_line WHERE source_id='israel';" 2>/dev/null || echo "0")
n_lincoln=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM map_strike_line WHERE source_id='lincoln';" 2>/dev/null || echo "0")
n_ford=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM map_strike_line WHERE source_id='ford';" 2>/dev/null || echo "0")

echo ""
echo "key_location:"
echo "  us   (美军基地等): 当前 $n_us 条，期望 $EXPECT_US 条"
echo "  iran (伊朗被袭点): 当前 $n_iran 条，期望 $EXPECT_IRAN 条"
echo ""
echo "map_strike_line (盟军打击伊朗):"
echo "  israel: 当前 $n_israel 条，期望 $EXPECT_ISRAEL 条"
echo "  lincoln: 当前 $n_lincoln 条，期望 $EXPECT_LINCOLN 条"
echo "  ford:   当前 $n_ford 条，期望 $EXPECT_FORD 条"
echo "=========================================="

ok=0
[[ "$n_us" -ge "$EXPECT_US" ]] && [[ "$n_iran" -ge "$EXPECT_IRAN" ]] && \
[[ "$n_israel" -ge "$EXPECT_ISRAEL" ]] && [[ "$n_lincoln" -ge "$EXPECT_LINCOLN" ]] && \
[[ "$n_ford" -ge "$EXPECT_FORD" ]] && ok=1

if [[ $ok -eq 1 ]]; then
  echo "结论: 攻击地点/打击线数量正常"
  exit 0
fi

echo "结论: 数量不足，请在生产执行 seed 以与当前代码一致："
echo "  cd $PROJECT_ROOT"
echo "  cp server/data.db server/data.db.bak-\$(date +%Y%m%d-%H%M%S)"
echo "  DB_PATH=server/data.db node server/seed.js"
echo "  重启 API 后刷新页面"
exit 1
