#!/usr/bin/env python3
"""Shrink generated art for shipping.

- chroma-keyed gameplay sprites: downscale (they draw at <=230 logical px),
  keep PNG so the runtime magenta keying stays clean.
- background plates: downscale + convert to JPEG (painterly plates compress
  beautifully); the matching .png is removed. assets.ts loads bg-*.jpg.

Idempotent: skips anything already at target size / already converted.
"""
import os
from PIL import Image

ROOT = os.path.join(os.path.dirname(__file__), '..', 'public', 'sprites')

SPRITE_MAX = {
    'player-idle.png': 512,
    'player-run.png': 512,
    'enemy-wisp.png': 512,
    'enemy-scuttler.png': 512,
    'pickup-stargrip.png': 512,
    'ground.png': 512,
    'platform.png': 512,
    'boss-orrery.png': 800,
}

BG_SIZE = (864, 1296)
BG_QUALITY = 82

for name, maxside in SPRITE_MAX.items():
    p = os.path.join(ROOT, name)
    if not os.path.exists(p):
        print(f'  [skip] {name} missing')
        continue
    im = Image.open(p)
    if max(im.size) <= maxside:
        print(f'  [ok]   {name} already {im.size}')
        continue
    ratio = maxside / max(im.size)
    im = im.resize((round(im.width * ratio), round(im.height * ratio)), Image.LANCZOS)
    im.save(p, optimize=True)
    print(f'  [png]  {name} -> {im.size}, {os.path.getsize(p)//1024} KB')

for name in os.listdir(ROOT):
    if not (name.startswith('bg-') and name.endswith('.png')):
        continue
    p = os.path.join(ROOT, name)
    out = p[:-4] + '.jpg'
    im = Image.open(p).convert('RGB')
    im = im.resize(BG_SIZE, Image.LANCZOS)
    im.save(out, quality=BG_QUALITY, optimize=True)
    os.remove(p)
    print(f'  [jpg]  {name} -> {os.path.basename(out)}, {os.path.getsize(out)//1024} KB')

print('done.')
