#!/usr/bin/env bash
# 从 Unity 主站导入 91601–93430 关卡（地图 + spawns + 主题 + 烘焙预制体）
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
UNITY_ROOT="${UNITY_ROOT:-/Users/liuyufei/tfrh/主站文件/主站}"
DB="$ROOT/assets/level-data/levels-database.json"
PREFAB_OUT="$ROOT/assets/bundle-level-prefabs/level-prefabs"
MIN_ID=91601
MAX_ID=93430

cd "$ROOT"

echo "==> [1/5] 导出 Unity 关卡 JSON (${MIN_ID}-${MAX_ID})"
python3 tools/export_all_levels.py \
  --unity-root "$UNITY_ROOT" \
  --output "$DB" \
  --merge-into "$DB" \
  --min-level-id "$MIN_ID" \
  --max-level-id "$MAX_ID"

echo "==> [2/5] 导入主题贴图（silu/snow/sanxing/chinese/redArmy/numMan）"
python3 tools/import_unity_textures.py \
  --unity-root "$UNITY_ROOT" \
  --themes silu,snow,sanxing,chinese,redArmy,numMan || true

echo "==> [3/5] 修复砖块 meta + 主题调色板"
python3 tools/fix_tile_texture_metas.py || true
python3 tools/build_theme_palettes.py --unity-root "$UNITY_ROOT" || true
python3 tools/sync_theme_nprop_ground.py 2>/dev/null || true

echo "==> [4/5] 烘焙 Cocos 关卡预制体 (${MIN_ID}-${MAX_ID})"
python3 tools/bake_cocos_level_prefabs.py \
  --db "$DB" \
  --out-dir "$PREFAB_OUT" \
  --min-level-id "$MIN_ID" \
  --max-level-id "$MAX_ID"

echo "==> [5/5] 校验"
python3 - <<'PY'
import json
from pathlib import Path
from collections import Counter
db = json.loads(Path("assets/level-data/levels-database.json").read_text())
themes = Counter()
empty = 0
missing = 0
kinds = Counter()
for lid in range(91601, 93431):
    L = db["levels"].get(str(lid))
    if not L:
        missing += 1
        continue
    if not L.get("spawns"):
        empty += 1
    themes[L.get("theme", "?")] += 1
    for s in L.get("spawns") or []:
        kinds[s.get("kind", "?")] += 1
prefabs = list(Path("assets/bundle-level-prefabs/level-prefabs").glob("Level*.prefab"))
in_range = [p for p in prefabs if 91601 <= int(p.stem.replace("Level", "")) <= 93430]
print(f"missing: {missing}/1830")
print(f"spawns empty: {empty}/1830")
print(f"themes: {dict(themes)}")
print(f"spawn kinds: {dict(kinds)}")
print(f"prefabs in range: {len(in_range)}/1830")
PY

echo "Done."
