#!/usr/bin/env python3
"""Build small, phone-friendly copies of DLR's large visual assets."""

from pathlib import Path
from PIL import Image


ROOT = Path(__file__).resolve().parents[1]
WEB = ROOT / "web"
OUT = WEB / "mobile"


def remove_magenta(image: Image.Image) -> Image.Image:
    im = image.convert("RGBA")
    px = im.load()
    for y in range(im.height):
        for x in range(im.width):
            r, g, b, a = px[x, y]
            if r > 120 and b > 110 and g + 32 < r and g + 32 < b:
                px[x, y] = (r, g, b, 0)
            elif g + 32 < r and g + 24 < b and b > 90:
                px[x, y] = (min(r, g + 22), g, min(b, g + 22), a)
    return im


def fit(image: Image.Image, max_side: int) -> Image.Image:
    scale = min(1.0, max_side / max(image.size))
    if scale == 1:
        return image
    size = tuple(max(1, round(v * scale)) for v in image.size)
    return image.resize(size, Image.Resampling.LANCZOS)


def save_webp(src: Path, dest: Path, max_side: int, transparent=False) -> None:
    image = Image.open(src)
    image = remove_magenta(image) if transparent else image.convert("RGB")
    image = fit(image, max_side)
    dest.parent.mkdir(parents=True, exist_ok=True)
    image.save(
        dest,
        "WEBP",
        lossless=transparent,
        quality=82,
        method=6,
        exact=transparent,
    )


def main() -> None:
    for src in sorted((WEB / "bodies").glob("*.png")):
        if "_" not in src.stem:  # idle body only; phone mode intentionally skips pose strips
            save_webp(src, OUT / "bodies" / f"{src.stem}.webp", 512, transparent=True)

    for src in sorted(WEB.glob("room*.png")):
        save_webp(src, OUT / f"{src.stem}.webp", 768)

    for src in sorted((WEB / "scenes").glob("*.png")):
        if not src.stem.startswith("_"):
            save_webp(src, OUT / "scenes" / f"{src.stem}.webp", 768)


if __name__ == "__main__":
    main()
