/**
 * 关卡注册表 — 统一从 LevelDatabase（单一 JSON）读取
 */
import { LevelConfig } from './LevelTypes';
import { LEVEL_ID_BASE } from './LevelIds';

export { LEVEL_ID_BASE, isGameLevelId } from './LevelIds';
import {
    getLevelConfig as dbGet,
    hasLevel as dbHas,
    getLevelIds as dbIds,
    getLevelCount as dbCount,
    nextLevelId as dbNext,
    prevLevelId as dbPrev,
    setLevel as dbSet,
    removeLevel as dbRemove,
    addLevel as dbAdd,
    loadLevelDatabase,
    isLevelDatabaseReady,
    MIN_LEVEL_ID as dbMin,
    MAX_LEVEL_ID as dbMax,
} from './LevelDatabase';

export { loadLevelDatabase, isLevelDatabaseReady };

export function getMinLevelId(): number {
    return isLevelDatabaseReady() ? dbMin() : LEVEL_ID_BASE;
}

export function getMaxLevelId(): number {
    return isLevelDatabaseReady() ? dbMax() : LEVEL_ID_BASE;
}

/**
 * 主站 SendMessage(levelID) → 查 Cocos 关卡库；无条目时按 Level{id}.prefab 加载。
 */
export function resolveLevelConfig(levelID: number): LevelConfig | null {
    const cfg = dbGet(levelID);
    if (cfg) return cfg;
    if (levelID <= 0) return null;
    return {
        levelID,
        boundary: { x: 20, y: 20 },
        spawns: [],
        cocosPrefab: `level-prefabs/Level${levelID}`,
        theme: 'sanxing',
    };
}

/** @deprecated 请用 getMinLevelId() / getMaxLevelId() */
export let MIN_LEVEL_ID = LEVEL_ID_BASE;
/** @deprecated 请用 getMaxLevelId() */
export let MAX_LEVEL_ID = LEVEL_ID_BASE;

export function refreshLevelIdBounds() {
    MIN_LEVEL_ID = getMinLevelId();
    MAX_LEVEL_ID = getMaxLevelId();
}

export function getLevelConfig(levelID: number): LevelConfig | null {
    return dbGet(levelID);
}

export function hasLevel(levelID: number): boolean {
    return dbHas(levelID);
}

export function registerLevel(config: LevelConfig) {
    dbSet(config);
}

export function addLevel(config: LevelConfig) {
    dbAdd(config);
}

export function removeLevel(levelID: number) {
    dbRemove(levelID);
}

export function getLevelCount(): number {
    return dbCount();
}

export function getLevelIds(): number[] {
    return dbIds();
}

export function nextLevelId(cur: number): number {
    return dbNext(cur);
}

export function prevLevelId(cur: number): number {
    return dbPrev(cur);
}
