package com.tiedup.remake.client.animation.tick;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Cache for MCA villager animation tick tracking.
 * Used by MixinVillagerEntityBaseModelMCA to prevent animations from ticking
 * multiple times per game tick.
 *
 * <p>This is extracted from the mixin so it can be cleared on world unload
 * to prevent memory leaks. Uses {@link ConcurrentHashMap} because reads
 * happen on the render thread (from the mixin's {@code setupAnim} tail
 * injection) while {@link #clear} is called from the main thread on world
 * unload — a plain {@code HashMap} could observe a torn state or throw
 * {@link java.util.ConcurrentModificationException} during the race.</p>
 */
@OnlyIn(Dist.CLIENT)
public final class MCAAnimationTickCache {

    private static final Map<UUID, Integer> lastTickMap =
        new ConcurrentHashMap<>();

    private MCAAnimationTickCache() {
        // Utility class
    }

    /**
     * Get the last tick value for an entity.
     * @param uuid Entity UUID
     * @return Last tick value, or -1 if not cached
     */
    public static int getLastTick(UUID uuid) {
        return lastTickMap.getOrDefault(uuid, -1);
    }

    /**
     * Set the last tick value for an entity.
     * @param uuid Entity UUID
     * @param tick Current tick value
     */
    public static void setLastTick(UUID uuid, int tick) {
        lastTickMap.put(uuid, tick);
    }

    /**
     * Clear all cached data.
     * Called on world unload to prevent memory leaks.
     */
    public static void clear() {
        lastTickMap.clear();
    }

    /** Drop the tick-dedup entry for an entity leaving the level. */
    public static void remove(UUID entityUuid) {
        lastTickMap.remove(entityUuid);
    }
}
