#!/usr/bin/env python3
"""props_import.py — turn raw generated art into game-ready prop sprites.

    python3 tools/props_import.py <raw-image> <kind> [--no-quantise]

Pipeline per docs/SPACES.md §4: crop to content, remove near-black/flat
background to alpha, nearest-neighbour downscale to the kind's target size,
optional 16-colour quantise (keeps the pixel-art register), write
public/props/<kind>.png and add <kind> to public/props/manifest.json.

Kinds and target sizes mirror PROP_SIZES in src/scenes/floor/FloorView.ts —
unknown kinds are refused so a typo cannot ship an orphan sprite.
"""
import json
import sys
from pathlib import Path

from PIL import Image

TARGETS = {
    "deck": (32, 32), "mixer": (32, 16), "monitor": (16, 16), "boothLamp": (16, 16),
    "speaker": (16, 32), "discoball": (32, 32),
    "barShelf": (496, 16), "taps": (48, 16), "till": (32, 16), "glassStack": (32, 16),
    "glassRack": (32, 16), "boothTable": (32, 16), "sinkRow": (96, 16),
    "buttBin": (16, 16), "crate": (16, 16),
    "poster1": (32, 16), "poster2": (32, 16), "poster3": (32, 16),
    "cloak": (16, 48), "stampPodium": (16, 16), "arcade": (32, 32),
    "highTable": (16, 16), "plant": (16, 16), "wetFloor": (16, 16), "poolTable": (48, 32),
    # the door-scene backdrop plate is special-cased: full size, no quantise
    "street:backdrop": (640, 176),
}

def main() -> None:
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    raw, kind = Path(sys.argv[1]), sys.argv[2]
    quantise = "--no-quantise" not in sys.argv
    if kind not in TARGETS:
        sys.exit(f"unknown kind '{kind}' — add it to PROP_SIZES + PROPS first, then here")

    img = Image.open(raw).convert("RGBA")
    # near-black background -> transparent (generated props sit on dark bg by prompt)
    px = img.load()
    for y in range(img.height):
        for x in range(img.width):
            r, g, b, a = px[x, y]
            if r < 18 and g < 18 and b < 22:
                px[x, y] = (0, 0, 0, 0)
    bbox = img.getbbox()
    if bbox:
        img = img.crop(bbox)

    w, h = TARGETS[kind]
    img = img.resize((w, h), Image.NEAREST)
    if quantise and kind != "street:backdrop":
        alpha = img.getchannel("A")
        img = img.convert("RGB").quantize(16).convert("RGBA")
        img.putalpha(alpha)

    out_name = kind.replace(":", "_")
    root = Path(__file__).resolve().parent.parent
    out = root / "public" / "props" / f"{out_name}.png"
    out.parent.mkdir(parents=True, exist_ok=True)
    img.save(out)

    man_path = root / "public" / "props" / "manifest.json"
    man = json.loads(man_path.read_text()) if man_path.exists() else {"props": []}
    if out_name not in man["props"]:
        man["props"].append(out_name)
        man["props"].sort()
    man_path.write_text(json.dumps(man, indent=2) + "\n")
    print(f"wrote {out} and updated manifest ({len(man['props'])} generated props live)")

if __name__ == "__main__":
    main()
