package com.tiedup.remake.v2.bondage.client;

import com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemDefinition;
import com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemRegistry;
import java.util.LinkedHashMap;
import java.util.Map;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Resolves per-item tint colors by merging definition defaults with NBT overrides.
 *
 * <p>Priority (highest wins):
 * <ol>
 *   <li>NBT tag {@code tint_colors} on the ItemStack (player dye overrides)</li>
 *   <li>Default tint channels from the {@link DataDrivenItemDefinition}</li>
 * </ol>
 *
 * <p>Returns a map of tint channel name (e.g. "tintable_0") to RGB int (0xRRGGBB).
 * An empty map means no tint — the renderer should use white (no color modification).</p>
 */
@OnlyIn(Dist.CLIENT)
public final class TintColorResolver {

    private TintColorResolver() {}

    /**
     * Resolve tint colors for an ItemStack.
     *
     * @param stack the equipped bondage item
     * @return channel-to-color map; empty if no tint channels defined or found
     */
    public static Map<String, Integer> resolve(ItemStack stack) {
        Map<String, Integer> result = new LinkedHashMap<>();

        // 1. Load defaults from DataDrivenItemDefinition
        DataDrivenItemDefinition def = DataDrivenItemRegistry.get(stack);
        if (def != null && def.tintChannels() != null) {
            result.putAll(def.tintChannels());
        }

        // 2. Override with NBT "tint_colors" (player dye overrides)
        CompoundTag tag = stack.getTag();
        if (tag != null && tag.contains("tint_colors", Tag.TAG_COMPOUND)) {
            CompoundTag tints = tag.getCompound("tint_colors");
            for (String key : tints.getAllKeys()) {
                result.put(key, tints.getInt(key));
            }
        }

        return result;
    }
}
