#!/usr/bin/env bash
# 【可选 · 仅参考】从 Unity 主站导入 spawns / boundary 到 Cocos levels-database.json
#
# 正常运行包不依赖 Unity。仅在需要对照 Unity Levels*.cs 批量补齐 spawn 时使用。
# 地图与贴图仍以 Cocos 预制体为准；本脚本默认不解析 Unity prefab 瓦片。
#
#   bash tools/sync-reference-from-unity.sh
#   bash tools/sync-reference-from-unity.sh "/path/to/主站"
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
UNITY_ROOT="${1:-$HOME/tfrh/主站文件/主站}"
TMP="$ROOT/assets/resources/level/.unity-reference-import.json"
OUT="$ROOT/assets/level-data/levels-database.json"

[[ -d "$UNITY_ROOT/Assets/Scripts/Core" ]] || {
  echo "错误: Unity 参考目录无效: $UNITY_ROOT" >&2
  exit 1
}

echo "==> [参考] 从 Unity 导入 spawns（不覆盖 Cocos 预制体地图）"
python3 "$ROOT/tools/export_all_levels.py" \
  --unity-root "$UNITY_ROOT" \
  --output "$TMP" \
  --skip-prefab-maps

python3 << PY
import json
from pathlib import Path

out = Path("$OUT")
ref = Path("$TMP")
db = json.loads(out.read_text(encoding="utf-8")) if out.is_file() else {"levels": {}}
unity = json.loads(ref.read_text(encoding="utf-8"))
merged = 0
for key, u in (unity.get("levels") or {}).items():
    cur = db.setdefault("levels", {}).setdefault(key, {})
    if u.get("spawns"):
        cur["spawns"] = u["spawns"]
        merged += 1
    if u.get("boundary"):
        cur["boundary"] = u["boundary"]
    if u.get("unityPrefab"):
        cur["unityPrefab"] = u["unityPrefab"]
    cur.setdefault("levelID", u.get("levelID", int(key)))
    cur.setdefault("cocosPrefab", u.get("cocosPrefab", f"level-prefabs/Level{key}"))
db["source"] = (db.get("source") or "") + " + unity-reference-spawns"
out.write_text(json.dumps(db, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"merged spawns for {merged} levels into {out}")
PY

rm -f "$TMP"
echo "==> 建议再运行: bash tools/sync-level-db.sh  （用 Cocos 预制体刷新地图/主题）"
