#!/usr/bin/env bash
# 看板板块数据快速检查：各表/API 与板块对应关系，便于逐项 debug
# 用法: ./scripts/debug-panels.sh
# 依赖: curl；可选 jq、sqlite3 以输出更清晰

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

echo "=========================================="
echo "看板板块数据检查 (DEBUG_PANELS)"
echo "API: $API_URL | DB: $DB_PATH"
echo "=========================================="
echo ""

# ---------- 1. API 健康与态势摘要 ----------
echo "[1] API 与态势摘要"
if ! curl -sf "$API_URL/api/health" >/dev/null 2>&1; then
  echo "  ✗ API 无响应，请先运行: npm run api"
  echo "  后续表检查将跳过（依赖 API 或直接读 DB）"
else
  echo "  ✓ API 正常"
  SIT=$(curl -sf "$API_URL/api/situation" 2>/dev/null || echo "{}")
  if command -v jq &>/dev/null; then
    echo "  lastUpdated:     $(echo "$SIT" | jq -r '.lastUpdated // "?"')"
    echo "  recentUpdates:    $(echo "$SIT" | jq -r '.recentUpdates | length') 条 → 事件脉络"
    echo "  conflictEvents:   $(echo "$SIT" | jq -r '.conflictEvents | length') 条 → 地图冲突点"
    echo "  us powerIndex:    $(echo "$SIT" | jq -r '.usForces.powerIndex.overall')  → 顶栏/战力图"
    echo "  iran powerIndex:  $(echo "$SIT" | jq -r '.iranForces.powerIndex.overall')"
    echo "  us keyLocations:  $(echo "$SIT" | jq -r '.usForces.keyLocations | length') 条 → 美国基地/地图"
    echo "  iran keyLocations: $(echo "$SIT" | jq -r '.iranForces.keyLocations | length') 条 → 伊朗基地/地图"
    echo "  us combatLosses:  killed=$(echo "$SIT" | jq -r '.usForces.combatLosses.personnelCasualties.killed') wounded=$(echo "$SIT" | jq -r '.usForces.combatLosses.personnelCasualties.wounded')"
    echo "  wallStreet points: $(echo "$SIT" | jq -r '.usForces.wallStreetInvestmentTrend | length')  → 华尔街图"
    echo "  retaliation:     $(echo "$SIT" | jq -r '.iranForces.retaliationSentiment') (history: $(echo "$SIT" | jq -r '.iranForces.retaliationSentimentHistory | length') 条)"
  else
    echo "  (安装 jq 可显示详细字段) 态势已拉取，长度: ${#SIT}"
  fi
fi
echo ""

# ---------- 2. 各表行数（直接读 DB）----------
echo "[2] 数据库表行数（与板块对应）"
if ! [[ -f "$DB_PATH" ]]; then
  echo "  ✗ 数据库文件不存在: $DB_PATH"
  echo "  请先 seed: node server/seed.js 或 启动 API 后由 initDb 创建"
elif ! command -v sqlite3 &>/dev/null; then
  echo "  (未安装 sqlite3，跳过表统计。可安装后重试)"
else
  TABLES="force_summary power_index force_asset key_location combat_losses wall_street_trend retaliation_current retaliation_history situation_update situation gdelt_events conflict_stats news_content"
  for t in $TABLES; do
    n=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM $t" 2>/dev/null || echo "?")
    case "$t" in
      force_summary)     desc="力量摘要(美/伊)" ;;
      power_index)       desc="战力指数 → 顶栏/战力图" ;;
      force_asset)        desc="资产列表 → 左右侧摘要" ;;
      key_location)       desc="据点 → 地图/美伊基地面板" ;;
      combat_losses)      desc="战损 → 战损面板" ;;
      wall_street_trend)  desc="华尔街趋势图" ;;
      retaliation_current) desc="报复当前值" ;;
      retaliation_history) desc="报复历史 → 仪表盘" ;;
      situation_update)   desc="事件脉络 → 时间线" ;;
      situation)          desc="updated_at → 顶栏时间" ;;
      gdelt_events)      desc="冲突点 → 地图图层" ;;
      conflict_stats)     desc="冲突统计 → 战损区" ;;
      news_content)      desc="资讯表 → /api/news" ;;
      *)                 desc="" ;;
    esac
    printf "  %-22s %6s  %s\n" "$t" "$n" "$desc"
  done
fi
echo ""

# ---------- 3. 板块健康简要判断 ----------
echo "[3] 板块数据来源与可能问题"
echo "  • 仅 seed、爬虫不写: force_summary, power_index, force_asset"
echo "  • 爬虫可更新: situation_update(事件脉络), key_location(基地状态), combat_losses(战损), retaliation_*, wall_street_trend, gdelt_events"
echo "  • 事件脉络不更新 → 检查爬虫是否启动、是否调用 POST /api/crawler/notify"
echo "  • 战损/基地不更新 → 检查是否跑 npm run gdelt、提取器是否输出、新闻是否含相关表述"
echo "  • 地图无冲突点 → 检查 gdelt_events 是否有数据、GDELT 或 RSS 回填是否执行"
echo ""
echo "详细逐板块说明见: docs/DEBUG_PANELS.md"
echo "=========================================="
