from pathlib import Path

from PIL import Image


ROOT = Path(__file__).resolve().parent
SOURCE = ROOT / "botania/assets/botania/textures/item/mana_pearl.png"
OUTPUT = ROOT.parents[1] / "assets/kubejs/textures/item"

# Seven hard colors match the seven opaque colors in Botania's Mana Pearl.
# The generated concepts define the mood; the original texture defines every
# final pixel, keeping all three pearls visibly related.
PURIFIED_PALETTE = [
    (73, 91, 104, 255),
    (103, 128, 144, 255),
    (142, 164, 177, 255),
    (180, 200, 210, 255),
    (216, 232, 237, 255),
    (244, 244, 232, 255),
    (255, 255, 255, 255),
]

BLOOD_PALETTE = [
    (50, 4, 17, 255),
    (78, 7, 27, 255),
    (112, 11, 38, 255),
    (151, 16, 49, 255),
    (193, 28, 59, 255),
    (235, 91, 107, 255),
    (255, 226, 225, 255),
]


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

    mapping = dict(zip(source_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)
    result.resize((256, 256), Image.Resampling.NEAREST).save(
        ROOT / output_name.replace(".png", "_preview.png")
    )


OUTPUT.mkdir(parents=True, exist_ok=True)
recolor("purified_pearl.png", PURIFIED_PALETTE)
recolor("blood_pearl.png", BLOOD_PALETTE)
