/**
 * 进关前按需加载：assets_all、主题/贴图元数据、关卡库分片。
 * 由 loader 注入 __tfrhEnsureAssetsCore / __tfrhEnsureLevelDbShard。
 */
import { ensureResourcesBundle } from './ResourcesBundle';
import { loadThemeDatabase } from '../theme/ThemeRegistry';
import { loadTileDisplayMeta } from '../visual/TileDisplayMeta';
import { ensureLevelShardLoaded } from '../level/LevelDatabase';

declare global {
    interface Window {
        __tfrhEnsureAssetsCore?: (onProgress?: (frac: number) => void) => Promise<void>;
        __tfrhEnsureLevelDbShard?: (levelId: number) => Promise<void>;
        __tfrhEnsureLevelPack?: (levelId: number) => Promise<void>;
    }
}

let runtimePrimed = false;

/** 首关 SwitchLevel 前拉齐运行时依赖（bootstrap 不再预载） */
export async function ensureRuntimeAssetsForLevel(levelId: number): Promise<void> {
    if (typeof window !== 'undefined') {
        if (window.__tfrhEnsureAssetsCore) {
            await window.__tfrhEnsureAssetsCore();
        }
        if (window.__tfrhEnsureLevelDbShard) {
            await window.__tfrhEnsureLevelDbShard(levelId);
        }
        if (window.__tfrhEnsureLevelPack) {
            await window.__tfrhEnsureLevelPack(levelId);
        }
    }
    await ensureResourcesBundle();
    if (!runtimePrimed) {
        await loadThemeDatabase();
        await loadTileDisplayMeta();
        runtimePrimed = true;
    }
    await ensureLevelShardLoaded(levelId);
}
