package com.tiedup.remake.client.gltf;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Lazy-loading cache for parsed glTF data.
 * Loads .glb files via Minecraft's ResourceManager on first access.
 */
@OnlyIn(Dist.CLIENT)
public final class GltfCache {

    private static final Logger LOGGER = LogManager.getLogger("GltfPipeline");
    private static final Map<ResourceLocation, GltfData> CACHE =
        new ConcurrentHashMap<>();

    private GltfCache() {}

    /**
     * Get parsed glTF data for a resource, loading it on first access.
     *
     * @param location resource location of the .glb file (e.g. "tiedup:models/gltf/v2/handcuffs/cuffs_prototype.glb")
     * @return parsed GltfData, or null if loading failed
     */
    public static GltfData get(ResourceLocation location) {
        GltfData cached = CACHE.get(location);
        if (cached != null) return cached;

        try {
            Resource resource = Minecraft.getInstance()
                .getResourceManager()
                .getResource(location)
                .orElse(null);
            if (resource == null) {
                LOGGER.error("[GltfPipeline] Resource not found: {}", location);
                return null;
            }

            try (InputStream is = resource.open()) {
                GltfData data = GlbParser.parse(is, location.toString());
                CACHE.put(location, data);
                return data;
            }
        } catch (Exception e) {
            LOGGER.error("[GltfPipeline] Failed to load GLB: {}", location, e);
            return null;
        }
    }

    /** Clear all cached data (call on resource reload). */
    public static void clearCache() {
        CACHE.clear();
        LOGGER.info("[GltfPipeline] Cache cleared");
    }

    /** Initialize the cache (called during FMLClientSetupEvent). */
    public static void init() {
        LOGGER.info("[GltfPipeline] GltfCache initialized");
    }
}
