#!/usr/bin/env bash
# 将关卡预制体从 resources 拆到独立 Asset Bundle（level-prefabs），减小 resources 包体积。
#
# 用法:
#   bash tools/migrate-level-prefab-bundle.sh          # 执行迁移
#   bash tools/migrate-level-prefab-bundle.sh --dry-run
#
# 迁移后请在 Cocos Creator 中重新构建 Web，再运行 package-for-project.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
SRC="$PROJECT_DIR/assets/resources/level-prefabs"
DST="$PROJECT_DIR/assets/bundle-level-prefabs/level-prefabs"
DRY_RUN=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) DRY_RUN=1; shift ;;
    -h|--help)
      echo "将 assets/resources/level-prefabs 移至 assets/bundle-level-prefabs/level-prefabs"
      exit 0
      ;;
    *) echo "未知参数: $1" >&2; exit 1 ;;
  esac
done

if [[ ! -d "$SRC" ]]; then
  echo "源目录不存在（可能已迁移）: $SRC" >&2
  exit 0
fi

PREFAB_COUNT="$(find "$SRC" -maxdepth 1 -name 'Level*.prefab' 2>/dev/null | wc -l | tr -d ' ')"
echo "==> 待迁移预制体: ${PREFAB_COUNT} 个"
echo "    $SRC"
echo " -> $DST"

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "（dry-run，未修改文件）"
  exit 0
fi

mkdir -p "$PROJECT_DIR/assets/bundle-level-prefabs"
mkdir -p "$(dirname "$DST")"

if [[ -d "$DST" ]]; then
  echo "错误: 目标已存在: $DST" >&2
  echo "若需重新迁移，请先手动删除 bundle-level-prefabs/level-prefabs" >&2
  exit 1
fi

mv "$SRC" "$DST"
rm -f "$PROJECT_DIR/assets/resources/level-prefabs.meta"

# 子目录 meta（Creator 会在下次打开时补全 uuid，此处提供基础结构）
cat > "$DST.meta" <<'META'
{
  "ver": "1.2.0",
  "importer": "directory",
  "imported": true,
  "uuid": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "files": [],
  "subMetas": {},
  "userData": {}
}
META

echo "==> 迁移完成。下一步:"
echo "  1. 打开 Cocos Creator，确认 bundle-level-prefabs 显示为 Asset Bundle「level-prefabs」"
echo "  2. 构建 Web Desktop"
echo "  3. bash tools/package-for-project.sh"
