package com.tiedup.remake.network.personality;

import com.tiedup.remake.core.SystemMessageManager;
import com.tiedup.remake.core.TiedUpMod;
// Discipline now only triggers dialogue, no personality effects
import com.tiedup.remake.dialogue.EntityDialogueManager;
import com.tiedup.remake.dialogue.EntityDialogueManager.DialogueCategory;
import com.tiedup.remake.entities.EntityDamsel;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.personality.DisciplineType;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet sent from client to server to apply discipline to an NPC.
 * Used for verbal discipline actions (Praise, Scold, Threaten) from the DialogueScreen.
 *
 * Training System V2: Verbal discipline support
 */
public class PacketDisciplineAction {

    /** Maximum range for discipline actions */
    private static final double MAX_RANGE = 32.0;

    private final int entityId;
    private final String disciplineTypeName;

    public PacketDisciplineAction(int entityId, DisciplineType type) {
        this.entityId = entityId;
        this.disciplineTypeName = type.name();
    }

    private PacketDisciplineAction(int entityId, String disciplineTypeName) {
        this.entityId = entityId;
        this.disciplineTypeName = disciplineTypeName;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(entityId);
        buf.writeUtf(disciplineTypeName, 32);
    }

    public static PacketDisciplineAction decode(FriendlyByteBuf buf) {
        return new PacketDisciplineAction(buf.readInt(), buf.readUtf(32));
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer sender = ctx.get().getSender();
                if (sender == null) return;
                handleServer(sender);
            });
        ctx.get().setPacketHandled(true);
    }

    private void handleServer(ServerPlayer sender) {
        // MEDIUM FIX: Rate limiting to prevent discipline spam exploit
        if (!PacketRateLimiter.allowPacket(sender, "action")) {
            return;
        }

        // Find the target entity
        Entity entity = sender.level().getEntity(entityId);
        if (!(entity instanceof EntityDamsel damsel)) {
            TiedUpMod.LOGGER.warn(
                "[PacketDisciplineAction] Entity {} not found or not a Damsel",
                entityId
            );
            return;
        }

        // Validate distance
        double distance = sender.distanceTo(damsel);
        if (distance > MAX_RANGE) {
            SystemMessageManager.sendToPlayer(
                sender,
                SystemMessageManager.MessageCategory.ERROR,
                "Target is too far away!"
            );
            return;
        }

        // Parse discipline type
        DisciplineType type;
        try {
            type = DisciplineType.valueOf(disciplineTypeName);
        } catch (IllegalArgumentException e) {
            TiedUpMod.LOGGER.warn(
                "[PacketDisciplineAction] Unknown discipline type: {}",
                disciplineTypeName
            );
            return;
        }

        // Only allow verbal discipline from this packet (Praise, Scold, Threaten)
        if (!type.isVerbal()) {
            TiedUpMod.LOGGER.warn(
                "[PacketDisciplineAction] Non-verbal discipline {} attempted via packet",
                type.name()
            );
            return;
        }

        // Show appropriate dialogue
        DialogueCategory category = switch (type) {
            case PRAISE -> DialogueCategory.PRAISE_RESPONSE;
            case SCOLD -> DialogueCategory.SCOLD_RESPONSE;
            case THREATEN -> DialogueCategory.THREATEN_RESPONSE;
            default -> DialogueCategory.SCOLD_RESPONSE;
        };
        EntityDialogueManager.talkTo(damsel, sender, category);

        // Send feedback
        String npcName = damsel.getNpcName();
        String actionDesc = switch (type) {
            case PRAISE -> "praised";
            case SCOLD -> "scolded";
            case THREATEN -> "threatened";
            default -> "disciplined";
        };

        SystemMessageManager.sendToPlayer(
            sender,
            SystemMessageManager.MessageCategory.INFO,
            "You " + actionDesc + " " + npcName + "."
        );

        TiedUpMod.LOGGER.debug(
            "[PacketDisciplineAction] {} {} {}",
            sender.getName().getString(),
            actionDesc,
            npcName
        );
    }
}
