package com.tiedup.remake.dialogue;

import com.tiedup.remake.core.TiedUpMod;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.profiling.ProfilerFiller;

/**
 * Forge reload listener for dialogue JSON files.
 *
 * Integrates with Minecraft's resource reload system to:
 * 1. Load dialogue definitions from assets on server start
 * 2. Reload dialogues when /reload command is executed
 *
 * Registered via AddReloadListenerEvent in TiedUpMod.
 *
 * Personality System: Data-driven dialogue
 */
public class DialogueReloadListener implements PreparableReloadListener {

    @Override
    public CompletableFuture<Void> reload(
        PreparationBarrier barrier,
        ResourceManager resourceManager,
        ProfilerFiller preparationsProfiler,
        ProfilerFiller reloadProfiler,
        Executor backgroundExecutor,
        Executor gameExecutor
    ) {
        // Load dialogues in background thread (non-blocking)
        return CompletableFuture.runAsync(
            () -> {
                preparationsProfiler.startTick();
                preparationsProfiler.push("tiedup_dialogue_loading");

                try {
                    TiedUpMod.LOGGER.info(
                        "[DialogueReloadListener] Starting dialogue reload..."
                    );

                    // Load dialogues from assets
                    DialogueManager.reload(resourceManager, "en_us");

                    TiedUpMod.LOGGER.info(
                        "[DialogueReloadListener] Dialogue reload complete - {} IDs loaded",
                        DialogueManager.getDialogueCount()
                    );
                } catch (Exception e) {
                    TiedUpMod.LOGGER.error(
                        "[DialogueReloadListener] Failed to reload dialogues",
                        e
                    );
                }

                preparationsProfiler.pop();
                preparationsProfiler.endTick();
            },
            backgroundExecutor
        ).thenCompose(barrier::wait);
    }
}
