package com.tiedup.remake.network.armorstand;

import com.tiedup.remake.entities.armorstand.ArmorStandBondageClientCache;
import com.tiedup.remake.network.base.AbstractClientPacket;
import com.tiedup.remake.v2.BodyRegionV2;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Packet to synchronize armor stand bondage data to clients.
 *
 * Direction: Server -> Client (S2C)
 *
 * Sent when:
 * - A bondage item is equipped to an armor stand
 * - A bondage item is removed from an armor stand
 * - A player joins and armor stands with bondage items are loaded
 *
 * <p>Wire format (Epic 7D): uses {@link BodyRegionV2} enum for region identification.
 */
public class PacketSyncArmorStandBondage extends AbstractClientPacket {

    private final int entityId;
    private final BodyRegionV2 region;
    private final ItemStack item;

    /**
     * Create a sync packet for a single slot update.
     *
     * @param entityId The armor stand entity ID
     * @param region The body region
     * @param item The item in the slot (empty to clear)
     */
    public PacketSyncArmorStandBondage(
        int entityId,
        BodyRegionV2 region,
        ItemStack item
    ) {
        this.entityId = entityId;
        this.region = region;
        this.item = item != null ? item : ItemStack.EMPTY;
    }

    /**
     * Encode the packet to a byte buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeVarInt(entityId);
        buf.writeEnum(region);

        if (item.isEmpty()) {
            buf.writeBoolean(false);
        } else {
            buf.writeBoolean(true);
            buf.writeNbt(item.save(new CompoundTag()));
        }
    }

    /**
     * Decode the packet from a byte buffer.
     */
    public static PacketSyncArmorStandBondage decode(FriendlyByteBuf buf) {
        int entityId = buf.readVarInt();
        BodyRegionV2 region = buf.readEnum(BodyRegionV2.class);

        ItemStack item;
        if (buf.readBoolean()) {
            CompoundTag tag = buf.readNbt();
            item = tag != null ? ItemStack.of(tag) : ItemStack.EMPTY;
        } else {
            item = ItemStack.EMPTY;
        }

        return new PacketSyncArmorStandBondage(entityId, region, item);
    }

    @Override
    @OnlyIn(Dist.CLIENT)
    protected void handleClientImpl() {
        // Update the client-side cache
        ArmorStandBondageClientCache.updateItem(entityId, region, item);
    }

    // Getters for debugging
    public int getEntityId() {
        return entityId;
    }

    public BodyRegionV2 getRegion() {
        return region;
    }

    public ItemStack getItem() {
        return item;
    }
}
