"""Crops / scales the game's screenshots into the site's pictures, og.png, favicon and the thumbnail."""
import sys, os
from PIL import Image

src, game = sys.argv[1], sys.argv[2]
img = os.path.join(game, 'site', 'images')
os.makedirs(img, exist_ok=True)

def load(name):
    return Image.open(os.path.join(src, name + '.png')).convert('RGB')

def logo(width):
    # the logo of the art pack (var/art-preview/logo.png, magenta = transparent), scaled by whole factors
    im = Image.open(os.path.join(game, 'var', 'art-preview', 'logo.png')).convert('RGBA')
    px = im.load()
    for y in range(im.height):
        for x in range(im.width):
            if px[x, y][:3] == (255, 0, 255):
                px[x, y] = (0, 0, 0, 0)
    k = max(1, round(width / im.width))
    return im.resize((im.width * k, im.height * k), Image.NEAREST)

def native(im):
    # the shots are the 320x200 picture scaled: back to whole pixels, then x3 nearest
    return im.resize((320, 200), Image.NEAREST)

for name in ['hall', 'courtyard', 'plant', 'yard', 'cavern', 'warden', 'fight', 'title']:
    native(load(name)).resize((960, 600), Image.NEAREST).save(os.path.join(img, name + '.png'), optimize=True)

# Open Graph 1200 x 630: the warden fight with the logo strip of the title screen
og = Image.new('RGB', (1200, 630), (12, 4, 4))
war = native(load('warden')).crop((0, 0, 320, 168)).resize((1200, 630), Image.NEAREST)
og.paste(war, (0, 0))
lg = logo(800)
og.paste(lg, ((1200 - lg.width) // 2, 30), lg)
og.save(os.path.join(img, 'og.png'), optimize=True)

# thumbnail 16:9 for the games directory: the plant's fight, without the status bar
th = native(load('yard')).crop((0, 0, 320, 168)).crop((10, 0, 309, 168)).resize((640, 360), Image.NEAREST)
lg = logo(400)
th.paste(lg, ((640 - lg.width) // 2, 14), lg)
th.save(os.path.join(game, 'assets', 'thumbnail.png'), optimize=True)

# favicon / icon: the helmet of the status bar
helmet = native(load('hall')).crop((153, 170, 185, 200)).resize((64, 60), Image.NEAREST)
fav = Image.new('RGB', (64, 64), (20, 8, 8)); fav.paste(helmet, (0, 2))
fav.save(os.path.join(img, 'favicon.png'))
fav.resize((256, 256), Image.NEAREST).save(os.path.join(game, 'assets', 'icon.png'))
print('site images ok')

# hero background of the page: the warden's arena, no logo, no status bar
native(load('warden')).crop((0, 0, 320, 168)).resize((1280, 672), Image.NEAREST).save(os.path.join(img, 'hero.png'), optimize=True)
print('hero ok')
