"""Builds the site's pictures from the screenshots of the game tests (run bin/jumphp test cryo-studio first):
   python3 tools/site/images.py   (needs Pillow)"""
import os
from PIL import Image

root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
tests = os.path.join(root, 'var/screenshots/tests')
out = os.path.join(root, 'site/images')
# site picture => screenshot of a test ($this->game->shot('<name>'))
shots = {
    'leaks': 'leaks',               # MainFormTest: the leaking line, its creation and write lines
    'cache': 'leaks-cache',         # LeaksTest: the bounded cache, kept by another line
    'bystack': 'leaks-stack',       # LeaksTest: grouped by allocation stack
    'overview': 'overview-alert',   # OverviewTest: alerts of the heuristics
    'classes': 'classes',           # ClassesInspectorTest: classes by retained size, instances
    'inspector': 'inspector',       # ClassesInspectorTest: a node, its edges, its path to a root
    'dominators': 'dominators',     # GraphViewsTest
    'orphans': 'orphans',           # GraphViewsTest
    'dupes': 'dupes',               # GraphViewsTest
    'query': 'query',               # QuerySeriesTest
    'series': 'series',             # QuerySeriesTest: memory curve of a .cryom series
    'stack': 'stack',               # StackTest: frames and variables of a freeze file
    'live': 'live-snapshots',       # LiveTest: a running script's memory, two snapshots taken from it
}
keep = set(f'{n}.jpg' for n in shots) | {'og.png', 'favicon.png', 'logo.png'}
for name in os.listdir(out):
    if name not in keep:
        os.remove(os.path.join(out, name))
for name, shot in shots.items():
    im = Image.open(os.path.join(tests, f'{shot}.png')).convert('RGB')
    im.resize((1024, round(im.height * 1024 / im.width)), Image.LANCZOS).save(os.path.join(out, f'{name}.jpg'), quality=88)

leaks = Image.open(os.path.join(tests, 'leaks.png')).convert('RGB')
def cover(im, w, h):
    s = max(w / im.width, h / im.height)
    im = im.resize((round(im.width * s), round(im.height * s)), Image.LANCZOS)
    return im.crop((0, 0, w, h))
cover(leaks, 1200, 630).save(os.path.join(out, 'og.png'))
cover(leaks, 640, 360).save(os.path.join(root, 'assets/thumbnail.png'))
logo = Image.open(os.path.join(root, 'assets/images/logo.png'))
logo.resize((64, 64), Image.LANCZOS).save(os.path.join(out, 'favicon.png'))
logo.save(os.path.join(out, 'logo.png'))
