package com.tiedup.remake.worldgen;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Server-side resource reload listener that scans {@code data/<namespace>/tiedup_room_themes/}
 * for JSON files and populates the {@link RoomThemeRegistry}.
 *
 * <p>Room themes are server-authoritative only (used during worldgen). Unlike furniture,
 * there is no client sync packet -- the registry is atomically replaced via
 * {@link RoomThemeRegistry#reload(Map)} on each reload.</p>
 *
 * <p>Registered via {@link net.minecraftforge.event.AddReloadListenerEvent} in
 * {@link com.tiedup.remake.core.TiedUpMod.ForgeEvents}.</p>
 */
public class RoomThemeReloadListener
    extends SimplePreparableReloadListener<Void>
{

    private static final Logger LOGGER = LogManager.getLogger("TiedUpWorldgen");

    /** Resource directory containing room theme definition JSON files (under data/). */
    private static final String DIRECTORY = "tiedup_room_themes";

    @Override
    protected Void prepare(
        ResourceManager resourceManager,
        ProfilerFiller profiler
    ) {
        // No preparation needed -- parsing happens in apply phase
        return null;
    }

    @Override
    protected void apply(
        Void nothing,
        ResourceManager resourceManager,
        ProfilerFiller profiler
    ) {
        Map<ResourceLocation, RoomThemeDefinition> newDefs = new HashMap<>();

        Map<ResourceLocation, Resource> resources =
            resourceManager.listResources(DIRECTORY, loc ->
                loc.getPath().endsWith(".json")
            );

        int skipped = 0;

        for (Map.Entry<ResourceLocation, Resource> entry : resources.entrySet()) {
            ResourceLocation fileId = entry.getKey();
            Resource resource = entry.getValue();

            // Derive clean ID from file path: "tiedup:tiedup_room_themes/oubliette.json" -> "tiedup:oubliette"
            String rawPath = fileId.getPath();
            String cleanPath = rawPath.substring(rawPath.indexOf(DIRECTORY + "/") + DIRECTORY.length() + 1);
            if (cleanPath.endsWith(".json")) {
                cleanPath = cleanPath.substring(0, cleanPath.length() - 5);
            }
            ResourceLocation cleanId = ResourceLocation.fromNamespaceAndPath(fileId.getNamespace(), cleanPath);

            try (InputStream input = resource.open()) {
                RoomThemeDefinition def = RoomThemeParser.parse(input, cleanId);

                if (def != null) {
                    // Check for duplicate IDs (fileId IS the ID for room themes)
                    if (newDefs.containsKey(def.id())) {
                        LOGGER.warn(
                            "[TiedUpWorldgen] Server: Duplicate room theme ID '{}' from file '{}' -- overwriting previous definition",
                            def.id(),
                            fileId
                        );
                    }

                    newDefs.put(def.id(), def);
                    LOGGER.debug(
                        "[TiedUpWorldgen] Server loaded room theme: {}",
                        def.id()
                    );
                } else {
                    skipped++;
                }
            } catch (Exception e) {
                LOGGER.error(
                    "[TiedUpWorldgen] Server: Failed to read resource {}: {}",
                    fileId,
                    e.getMessage()
                );
                skipped++;
            }
        }

        // Atomically replace all definitions in the registry
        RoomThemeRegistry.reload(newDefs);

        LOGGER.info(
            "[TiedUpWorldgen] Server loaded {} room theme definitions ({} skipped) from {} JSON files",
            newDefs.size(),
            skipped,
            resources.size()
        );
    }
}
