#!/usr/bin/env bash
# 检查「关卡分包迁移」与 Cocos 构建是否一致
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
BUILD_DIR="${1:-$PROJECT_DIR/build/web-desktop}"

SRC_BUNDLE="$PROJECT_DIR/assets/bundle-level-prefabs/level-prefabs"
LEGACY="$PROJECT_DIR/assets/resources/level-prefabs"
BUILD_RESOURCES="$BUILD_DIR/assets/resources"
BUILD_LEVELS="$BUILD_DIR/assets/level-prefabs"

err=0

if [[ -d "$SRC_BUNDLE" ]]; then
  echo "✓ 工程已迁移: bundle-level-prefabs/level-prefabs"
  if [[ -d "$LEGACY" ]]; then
    echo "✗ 仍存在旧目录 resources/level-prefabs，请删除或重新运行 migrate-level-prefab-bundle.sh" >&2
    err=1
  fi
elif [[ -d "$LEGACY" ]]; then
  echo "○ 尚未迁移关卡分包（prefab 仍在 resources 内）"
  echo "  运行: bash tools/migrate-level-prefab-bundle.sh"
  exit 2
else
  echo "✗ 未找到任何关卡预制体目录" >&2
  exit 1
fi

[[ -f "$BUILD_DIR/index.js" ]] || {
  echo "✗ 缺少 Cocos 构建: $BUILD_DIR" >&2
  echo "  请在 Cocos Creator 中: 项目 → 构建 → Web Desktop → 构建" >&2
  exit 1
}

if [[ -d "$BUILD_LEVELS" ]]; then
  rs=$(du -sh "$BUILD_RESOURCES" 2>/dev/null | awk '{print $1}')
  ls=$(du -sh "$BUILD_LEVELS" 2>/dev/null | awk '{print $1}')
  echo "✓ 构建已含分包: assets/resources ($rs) + assets/level-prefabs ($ls)"
  exit 0
fi

echo "✗ 构建未刷新（仍只有 resources，无 assets/level-prefabs）" >&2
if [[ -d "$BUILD_RESOURCES" ]]; then
  du -sh "$BUILD_RESOURCES" 2>/dev/null || true
fi
echo "" >&2
echo "  迁移后必须重新构建 Web Desktop：" >&2
echo "  1. 打开 Cocos Creator → 项目 tfrh001" >&2
echo "  2. 确认资源管理器中 bundle-level-prefabs 标记为 Asset Bundle「level-prefabs」" >&2
echo "  3. 菜单 项目 → 构建发布 → Web Desktop → 构建" >&2
exit 3
