package com.tiedup.remake.client.events;

import com.mojang.logging.LogUtils;
import com.tiedup.remake.client.animation.BondageAnimationManager;
import com.tiedup.remake.client.animation.PendingAnimationManager;
import com.tiedup.remake.core.TiedUpMod;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.event.entity.EntityLeaveLevelEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.slf4j.Logger;

/**
 * Automatic cleanup handler for entity-related resources.
 *
 * <p>This handler automatically cleans up animation layers and pending animations
 * when entities leave the world, preventing memory leaks from stale cache entries.
 *
 * <p>Phase: Performance & Memory Management
 *
 * <p>Previously, cleanup had to be called manually via {@link BondageAnimationManager#cleanup(java.util.UUID)},
 * which was error-prone and could lead to memory leaks if forgotten.
 * This handler ensures cleanup happens automatically on entity removal.
 */
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE,
    value = Dist.CLIENT
)
public class EntityCleanupHandler {

    private static final Logger LOGGER = LogUtils.getLogger();

    /**
     * Automatically clean up animation resources when an entity leaves the world.
     *
     * <p>This event fires when:
     * <ul>
     *   <li>An entity is removed from the world (killed, despawned, unloaded)</li>
     *   <li>A player logs out</li>
     *   <li>A chunk is unloaded and its entities are removed</li>
     * </ul>
     *
     * <p>Cleanup includes:
     * <ul>
     *   <li>Removing animation layers from {@link BondageAnimationManager}</li>
     *   <li>Removing pending animations from {@link PendingAnimationManager}</li>
     * </ul>
     *
     * @param event The entity leave level event
     */
    @SubscribeEvent
    public static void onEntityLeaveLevel(EntityLeaveLevelEvent event) {
        // Only process on client side
        if (!event.getLevel().isClientSide()) {
            return;
        }

        // Clean up animation layers
        BondageAnimationManager.cleanup(event.getEntity().getUUID());

        // Clean up pending animation queue
        PendingAnimationManager.remove(event.getEntity().getUUID());

        LOGGER.debug(
            "Auto-cleaned animation resources for entity: {} (type: {})",
            event.getEntity().getUUID(),
            event.getEntity().getClass().getSimpleName()
        );
    }
}
