import { ProgressiveRegionPopulationApplication } from "../features/region-population/applications/ProgressiveRegionPopulationApplication.js";
import { PopulationProviderRegistry } from "../features/region-population/services/PopulationProviderRegistry.js";
import { RegionProviderRegistry } from "../features/region-population/services/RegionProviderRegistry.js";
import { RegionPopulationClearService } from "../features/region-population/services/RegionPopulationClearService.js";
import { RegionPopulationRunStore } from "../features/region-population/services/RegionPopulationRunStore.js";
import { RegionChronicleService } from "../features/region-population/services/RegionChronicleService.js";
import { ChronicleNarrativeModel } from "../features/region-population/models/ChronicleNarrativeModel.js";

const applications = new Map();
let lifecycleHookRegistered = false;

function ensureLifecycleHook() {
    if (lifecycleHookRegistered) return;
    lifecycleHookRegistered = true;
    Hooks.on("canvasReady", activeCanvas => {
        const activeSceneId = activeCanvas?.scene?.id || canvas.scene?.id || "";
        for (const [sceneId, application] of applications) {
            if (sceneId === activeSceneId) continue;
            applications.delete(sceneId);
            void application.close();
        }
    });
}

export function registerRegionProvider(providerId, definition) {
    return RegionProviderRegistry.register(providerId, definition);
}

export function unregisterRegionProvider(providerId) {
    return RegionProviderRegistry.unregister(providerId);
}

export function registerPopulationProvider(providerId, definition) {
    return PopulationProviderRegistry.register(providerId, definition);
}

export function unregisterPopulationProvider(providerId) {
    return PopulationProviderRegistry.unregister(providerId);
}

export function canPopulateRegion(scene = canvas.scene) {
    const regionProvider = RegionProviderRegistry.findForScene(scene);
    return !!regionProvider && PopulationProviderRegistry.listForScene(scene, regionProvider).length > 0;
}

export function getRegionPopulationRun(scene = canvas.scene) {
    return RegionPopulationRunStore.get(scene);
}

export function hasRegionChronicle(scene = canvas.scene) {
    return !!RegionChronicleService.getEntry(scene);
}

export function openRegionChronicle(scene = canvas.scene) {
    if (!scene?.id) return false;
    return RegionChronicleService.open(scene);
}

export function createChronicleNarrative(text, participants = []) {
    return ChronicleNarrativeModel.create(text, participants);
}
export function openRegionPopulation(scene = canvas.scene) {
    if (!scene?.id || !canPopulateRegion(scene)) return null;
    ensureLifecycleHook();
    let application = applications.get(scene.id);
    if (!application) {
        application = new ProgressiveRegionPopulationApplication({ sceneId: scene.id });
        applications.set(scene.id, application);
    }
    application.prepareToOpen();
    application.render({ force: true });
    return application;
}

export async function closeRegionPopulation(scene = canvas.scene) {
    const application = applications.get(scene?.id);
    if (!application) return false;
    applications.delete(scene.id);
    await application.close();
    return true;
}

export function clearRegionPopulation(scene = canvas.scene, options = {}) {
    return RegionPopulationClearService.clear(scene, { purpose: "clear", ...options });
}
