package com.tiedup.remake.network.conversation;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.dialogue.IDialogueSpeaker;
import com.tiedup.remake.dialogue.conversation.ConversationManager;
import com.tiedup.remake.network.PacketRateLimiter;
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 request opening a conversation.
 * Sent when player clicks the "Ask..." button in DialogueScreen.
 *
 *
 * DISABLED: Conversation system not in use. Kept because it is still registered
 * in ModNetwork — removing a registered packet would shift packet IDs.
 */
public class PacketRequestConversation {

    /** Maximum distance for conversation request */
    private static final double MAX_DISTANCE = 6.0;

    private final int entityId;

    public PacketRequestConversation(int entityId) {
        this.entityId = entityId;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(entityId);
    }

    public static PacketRequestConversation decode(FriendlyByteBuf buf) {
        int entityId = buf.readInt();
        return new PacketRequestConversation(entityId);
    }

    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) {
        if (!PacketRateLimiter.allowPacket(sender, "action")) return;

        // Find the target entity
        Entity entity = sender.level().getEntity(entityId);
        if (entity == null) {
            TiedUpMod.LOGGER.warn(
                "[PacketRequestConversation] Entity {} not found",
                entityId
            );
            return;
        }

        // Check if entity is a dialogue speaker
        if (!(entity instanceof IDialogueSpeaker speaker)) {
            TiedUpMod.LOGGER.warn(
                "[PacketRequestConversation] Entity {} is not a dialogue speaker",
                entityId
            );
            return;
        }

        // Validate distance
        double distance = sender.distanceTo(entity);
        if (distance > MAX_DISTANCE) {
            TiedUpMod.LOGGER.warn(
                "[PacketRequestConversation] Player {} too far from entity {} ({})",
                sender.getName().getString(),
                entityId,
                distance
            );
            return;
        }

        TiedUpMod.LOGGER.info(
            "[PacketRequestConversation] {} requesting conversation with {}",
            sender.getName().getString(),
            speaker.getDialogueName()
        );

        // Open the conversation - this will send PacketOpenConversation to client
        boolean success = ConversationManager.openConversation(speaker, sender);

        if (!success) {
            TiedUpMod.LOGGER.warn(
                "[PacketRequestConversation] Failed to open conversation with {}",
                speaker.getDialogueName()
            );
        }
    }

    public int getEntityId() {
        return entityId;
    }
}
