/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.dungeon.config;

import com.remains_cave.RemainsCaveMod;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.profiling.ProfilerFiller;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.event.AddReloadListenerEvent;
import org.jetbrains.annotations.NotNull;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

public class VaultRewardLoader {
    private static final Map<String, VaultRewardConfig> CACHE = new HashMap<>();

    public static VaultRewardConfig load(String path) {
        if (CACHE.containsKey(path)) {
            return CACHE.get(path);
        }

        String resourcePath = "/data/remains_cave/loot_table/vault_rewards/" + path;
        try (InputStream is = VaultRewardLoader.class.getResourceAsStream(resourcePath)) {
            if (is == null) {
                throw new RuntimeException("Vault reward config not found: " + resourcePath);
            }
            Yaml yaml = new Yaml();
            VaultRewardConfig config = yaml.loadAs(is, VaultRewardConfig.class);
            CACHE.put(path, config);
            return config;
        } catch (Exception e) {
            throw new RuntimeException("Failed to load vault reward config: " + path, e);
        }
    }

    // 资源重载监听器：清空缓存
    private static final PreparableReloadListener RELOAD_LISTENER = new PreparableReloadListener() {
        @Override
        public @NotNull CompletableFuture<Void> reload(PreparationBarrier barrier, @NotNull ResourceManager manager,
                                                       @NotNull ProfilerFiller prepareProfiler, @NotNull ProfilerFiller applyProfiler,
                                                       @NotNull Executor prepareExecutor, @NotNull Executor applyExecutor) {
            return barrier.wait(manager)
                    .thenRunAsync(() -> {
                        CACHE.clear();
                    }, applyExecutor);
        }
    };

    // 事件总线订阅，注册监听器（不再需要指定 bus，默认注册到 FORGE 总线）
    @EventBusSubscriber(modid = RemainsCaveMod.MODID)
    public static class Events {
        @SubscribeEvent
        public static void onAddReloadListeners(AddReloadListenerEvent event) {
            event.addListener(RELOAD_LISTENER);
        }
    }
}