from pathlib import Path

from PIL import Image


ROOT = Path(__file__).resolve().parent
VANILLA = ROOT / "vanilla/assets/minecraft/textures/item"
OUTPUT = ROOT.parents[1] / "assets/kubejs/textures/item"

# Palette derived from the generated concepts, deliberately reduced to the
# small, hard-edged color ramps used by vanilla 16x16 item textures.
INGOT_PALETTE = [
    (43, 9, 15, 255),
    (67, 13, 21, 255),
    (78, 16, 25, 255),
    (96, 21, 31, 255),
    (116, 27, 38, 255),
    (145, 43, 51, 255),
    (178, 77, 82, 255),
    (204, 151, 151, 255),
]

NUGGET_PALETTE = [
    (48, 9, 14, 255),
    (67, 13, 20, 255),
    (99, 20, 29, 255),
    (127, 29, 39, 255),
    (158, 45, 54, 255),
    (187, 79, 83, 255),
    (211, 151, 148, 255),
]


def recolor(source_name: str, output_name: str, palette: list[tuple[int, int, int, int]]) -> None:
    source = Image.open(VANILLA / source_name).convert("RGBA")
    opaque_colors = sorted(
        {pixel for pixel in source.getdata() if pixel[3]},
        key=lambda color: sum(color[:3]),
    )
    if len(opaque_colors) != len(palette):
        raise ValueError(f"Palette mismatch for {source_name}: {len(opaque_colors)} source colors")

    mapping = dict(zip(opaque_colors, palette))
    result = Image.new("RGBA", source.size, (0, 0, 0, 0))
    result.putdata([mapping.get(pixel, (0, 0, 0, 0)) for pixel in source.getdata()])
    result.save(OUTPUT / output_name)
    preview = result.resize((256, 256), Image.Resampling.NEAREST)
    preview.save(ROOT / output_name.replace(".png", "_preview.png"))


OUTPUT.mkdir(parents=True, exist_ok=True)
recolor("iron_ingot.png", "blood_infused_iron_ingot.png", INGOT_PALETTE)
recolor("gold_nugget.png", "blood_infused_iron_nugget.png", NUGGET_PALETTE)
