package com.tiedup.remake.mixin.client;

import com.tiedup.remake.compat.mca.MCACompat;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.IBondageState;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * Mixin for MCA's SpeechManager to block TTS when villager is gagged.
 *
 * <p>MCA's speech system works via TTS (Text-to-Speech) on the client side:
 * <ol>
 *   <li>Server sends VillagerMessage packet to client</li>
 *   <li>ClientInteractionManagerImpl.handleVillagerMessage() receives it</li>
 *   <li>SpeechManager.onChatMessage() is called</li>
 *   <li>TTS plays the sound</li>
 * </ol>
 *
 * <p>This mixin intercepts onChatMessage and cancels it if the villager is gagged.
 *
 * <p>Uses @Pseudo for soft dependency - only applies if MCA is present.
 * CLIENT SIDE ONLY.
 */
@Pseudo
@Mixin(targets = "forge.net.mca.client.tts.SpeechManager", remap = false)
public class MixinMCASpeechManager {

    /**
     * Inject at HEAD of onChatMessage to cancel TTS for gagged villagers.
     *
     * <p>MCA signature: void onChatMessage(Text text, UUID sender)
     * <p>Note: Text = net.minecraft.network.chat.Component (Yarn mapping)
     */
    @Inject(
        method = "onChatMessage",
        at = @At("HEAD"),
        cancellable = true,
        require = 0
    )
    private void tiedup$cancelGaggedSpeech(
        Component text,
        UUID sender,
        CallbackInfo ci
    ) {
        try {
            ClientLevel level = Minecraft.getInstance().level;
            if (level == null) return;

            // Find entity by UUID in rendered entities
            for (Entity entity : level.entitiesForRendering()) {
                if (
                    entity.getUUID().equals(sender) &&
                    entity instanceof LivingEntity living
                ) {
                    IBondageState state = MCACompat.getKidnappedState(living);
                    if (state != null && state.isGagged()) {
                        TiedUpMod.LOGGER.debug(
                            "[MCA] Blocked TTS for gagged villager: {}",
                            living.getName().getString()
                        );
                        ci.cancel();
                    }
                    break;
                }
            }
        } catch (Exception e) {
            TiedUpMod.LOGGER.debug(
                "[MCA] TTS cancellation check failed: {}",
                e.getMessage()
            );
        }
    }
}
