const providers = new Map();

export class PopulationProviderRegistry {
    static register(providerId, definition = {}) {
        const id = String(providerId || "").trim();
        if (!id) throw new Error("A population provider id is required.");
        if (typeof definition.runDevelopment !== "function") {
            throw new Error(`Population provider ${id} requires runDevelopment(context).`);
        }
        providers.set(id, { ...definition, id });
        Hooks.callAll("augurNexusPopulationProvidersChanged");
        return id;
    }

    static unregister(providerId) {
        const removed = providers.delete(String(providerId || "").trim());
        if (removed) Hooks.callAll("augurNexusPopulationProvidersChanged");
        return removed;
    }

    static get(providerId) {
        return providers.get(String(providerId || "").trim()) || null;
    }

    static listForScene(scene, regionProvider) {
        return [...providers.values()].filter(provider => {
            if (typeof provider.isAvailable !== "function") return true;
            try {
                return provider.isAvailable({ scene, regionProvider }) !== false;
            } catch (error) {
                console.warn(`Augur: Nexus | Population provider ${provider.id} availability failed.`, error);
                return false;
            }
        });
    }
}
