package com.tiedup.remake.compat.mca;

import com.tiedup.remake.compat.mca.capability.MCAKidnappedCapability;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.IRestrainable;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;

/**
 * MCA (Minecraft Comes Alive) compatibility module.
 * Proxy that delegates to MCAHandler only if mod is loaded.
 */
public class MCACompat {

    public static final Capability<MCAKidnappedCapability> MCA_KIDNAPPED =
        CapabilityManager.get(new CapabilityToken<>() {});
    public static final ResourceLocation MCA_KIDNAPPED_CAP_ID =
        ResourceLocation.fromNamespaceAndPath(
            TiedUpMod.MOD_ID,
            "mca_kidnapped"
        );
    private static final String MCA_MOD_ID = "mca";
    private static boolean mcaLoaded = false;

    public static void init() {
        mcaLoaded = ModList.get().isLoaded(MCA_MOD_ID);
        if (mcaLoaded) {
            TiedUpMod.LOGGER.info(
                "[MCA Compat] MCA detected! Initializing handler."
            );
            try {
                MCAHandler.init();
            } catch (Throwable e) {
                TiedUpMod.LOGGER.error(
                    "[MCA Compat] Failed to load MCA handler (class missing?)",
                    e
                );
                mcaLoaded = false;
            }
        }
    }

    public static boolean isMCALoaded() {
        return mcaLoaded;
    }

    public static boolean isMCAVillager(Entity entity) {
        return mcaLoaded && MCAHandler.isMCAVillager(entity);
    }

    @Nullable
    public static IRestrainable getKidnappedState(LivingEntity entity) {
        if (!mcaLoaded) return null;
        return MCAHandler.getKidnappedState(entity);
    }

    public static boolean shouldAttachCapability(Entity entity) {
        return isMCAVillager(entity);
    }

    public static void syncBondageState(LivingEntity entity) {
        MCABondageManager.getInstance().syncBondageState(entity);
    }

    @OnlyIn(Dist.CLIENT)
    public static void registerRenderLayers(
        EntityRenderersEvent.AddLayers event
    ) {
        if (!mcaLoaded) return;

        int layersAdded = 0;
        for (EntityType<
            ?
        > entityType : ForgeRegistries.ENTITY_TYPES.getValues()) {
            ResourceLocation typeId = ForgeRegistries.ENTITY_TYPES.getKey(
                entityType
            );
            if (
                typeId == null || !MCA_MOD_ID.equals(typeId.getNamespace())
            ) continue;

            // Check if it's a villager type
            if (!typeId.getPath().contains("villager")) continue;

            try {
                var renderer = event.getRenderer((EntityType) entityType);
                if (renderer != null) {
                    MCAHandler.addBondageLayer(renderer, event);
                    layersAdded++;
                }
            } catch (Exception e) {
                TiedUpMod.LOGGER.warn(
                    "[MCA Compat] Failed to add layer to {}: {}",
                    typeId,
                    e.getMessage()
                );
            }
        }

        if (layersAdded > 0) {
            TiedUpMod.LOGGER.info(
                "[MCA Compat] Added layers to {} MCA renderers",
                layersAdded
            );
        }
    }
}
