"""PLATE PYRAMID (A, 28 Oct, the pirate GPU stall): cut every export plate in img/maps/*.jpg into
   img/maps/pyr/<name>/h.jpg   half size      (drawn when the plate shows at 0.375-0.75 screen px per plate px)
   img/maps/pyr/<name>/q.jpg   quarter size   (below 0.375)
   img/maps/pyr/<name>/t_<col>_<row>.jpg   full-size tiles, T x T, each with OV px of its neighbours round it (seamless bilinear)
and write 58k_pyr58.js (window.K58_PYR: size, tile grid and the plate's edge fill per source). 58k_cine.js draws from the pyramid
when the manifest lists the plate (K58.PYR58 !== false); without it the old single-image path runs.
Run after any plate in img/maps changes:  python3 _tools/plate_pyr.py"""
import os, json, time
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
src_dir = os.path.join(here, 'img', 'maps'); out_dir = os.path.join(src_dir, 'pyr')
T, OV = 1024, 4
man = {}
def fill(im):
    s = im.resize((24, 24), Image.BILINEAR).convert('RGB'); px = s.load()
    def avg(y0, y1):
        r = g = b = n = 0
        for y in range(y0, y1):
            for i in range(24):
                if y > y0 and y < y1 - 1 and 0 < i < 23: continue
                c = px[i, y]; r += c[0]; g += c[1]; b += c[2]; n += 1
        return '#%02X%02X%02X' % (round(r / n), round(g / n), round(b / n))
    return {'top': avg(0, 12), 'bot': avg(12, 24)}
for f in sorted(os.listdir(src_dir)):
    if not f.endswith('.jpg'): continue
    name = f[:-4]; p = os.path.join(src_dir, f); im = Image.open(p).convert('RGB'); W, H = im.size
    d = os.path.join(out_dir, name); os.makedirs(d, exist_ok=True)
    h = im.resize((round(W / 2), round(H / 2)), Image.LANCZOS); h.save(os.path.join(d, 'h.jpg'), quality=90, optimize=True)
    q = h.resize((round(W / 4), round(H / 4)), Image.LANCZOS); q.save(os.path.join(d, 'q.jpg'), quality=90, optimize=True)
    cols, rows = (W + T - 1) // T, (H + T - 1) // T
    for cx in range(cols):
        for ry in range(rows):
            x0, y0 = max(0, cx * T - OV), max(0, ry * T - OV); x1, y1 = min(W, (cx + 1) * T + OV), min(H, (ry + 1) * T + OV)
            im.crop((x0, y0, x1, y1)).save(os.path.join(d, 't_%d_%d.jpg' % (cx, ry)), quality=92, optimize=True)
    man['img/maps/' + f] = {'w': W, 'h': H, 'T': T, 'ov': OV, 'cols': cols, 'rows': rows, 'dir': 'img/maps/pyr/' + name + '/', 'hw': h.size[0], 'hh': h.size[1], 'qw': q.size[0], 'qh': q.size[1], 'fill': fill(q), 'mt': int(os.path.getmtime(p))}
    print(f, W, H, cols, 'x', rows)
open(os.path.join(here, '58k_pyr58.js'), 'w').write('/* generated by _tools/plate_pyr.py at %s: the export plates cut into a pyramid (half, quarter, full-size tiles) */\nwindow.K58_PYR = %s;\n' % (time.strftime('%d %b %H:%M'), json.dumps(man, indent=0)))
print(len(man), 'plates')
