"""Convert a playable's png/jpg assets to WebP where that is smaller, and print the table.

Usage (from the playable's output folder):
    python build/webp_assets.py assets [--quality 88] [--keep]

Writes <name>.webp next to each png/jpg that gets smaller and deletes the original unless
--keep is given. Files where WebP is not smaller stay as they are. After this, update the
references in src/ (atlas.js, game.js, style.css) to the .webp names and rebuild.
Needs Pillow. WebP with alpha is supported by every mobile browser and ad webview since 2020.
"""
import argparse
import io
import os

from PIL import Image


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("folder")
    ap.add_argument("--quality", type=int, default=88)
    ap.add_argument("--keep", action="store_true", help="keep the png/jpg next to the webp")
    a = ap.parse_args()

    before = after = 0
    for name in sorted(os.listdir(a.folder)):
        if not name.lower().endswith((".png", ".jpg", ".jpeg")):
            continue
        path = os.path.join(a.folder, name)
        im = Image.open(path)
        buf = io.BytesIO()
        im.save(buf, "WEBP", quality=a.quality, method=6)
        src_size, webp_size = os.path.getsize(path), len(buf.getvalue())
        before += src_size
        if webp_size < src_size:
            out = os.path.splitext(path)[0] + ".webp"
            with open(out, "wb") as f:
                f.write(buf.getvalue())
            if not a.keep:
                os.remove(path)
            after += webp_size
            print(f"{src_size // 1024:6d} KB -> {webp_size // 1024:6d} KB  {name} -> {os.path.basename(out)}")
        else:
            after += src_size
            print(f"{src_size // 1024:6d} KB    kept       {name}")
    print(f"total {before // 1024} KB -> {after // 1024} KB")


if __name__ == "__main__":
    main()
