"""Measures each voice on the overlay sheet, render (column 0) against drawing (column 1), as fractions of figure height:
the figure's height and width, the visor's row, its width, the head's width on that row and the cheek beside the visor."""
import sys
from PIL import Image
im = Image.open(sys.argv[1] if len(sys.argv) > 1 else "toon-preview/rest/overlays.png").convert("RGB")
names = ["butler", "coach", "colleague", "homie", "squire"]
BG = (0xee, 0xee, 0xf4)
def is_bg(p): return sum(abs(a - b) for a, b in zip(p, BG)) < 30
def is_dark(p): return sum(p) < 130
def measure(x0, y0):
    px = im.load()
    rows = [y for y in range(512) if any(not is_bg(px[x0 + x, y0 + y]) for x in range(0, 512, 2))]
    top, bottom = rows[0], rows[-1]
    height = bottom - top
    cols = [x for x in range(512) if any(not is_bg(px[x0 + x, y0 + y]) for y in range(0, 512, 2))]
    width = cols[-1] - cols[0]
    best = None
    light = lambda x, y: 0 <= x < 512 and sum(px[x0 + x, y0 + y]) > 560
    for y in range(top, top + int(height * 0.45)):
        x = 0
        while x < 512:
            if not is_dark(px[x0 + x, y0 + y]):
                x += 1
                continue
            start = x
            while x < 512 and (is_dark(px[x0 + x, y0 + y]) or (x + 6 < 512 and is_dark(px[x0 + x + 6, y0 + y]))): x += 1
            run = (x - start, start, x)
            # A visor is a dark run with the head's cream on both sides of it.
            if run[0] > 30 and any(light(start - d, y) for d in range(1, 12)) and any(light(x + d, y) for d in range(1, 12)):
                if best is None or run[0] > best[1][0]: best = (y, run)
    y, (vw, vl, vr) = best
    def edge(step):
        x = vl if step < 0 else vr
        while 0 < x < 511 and not is_bg(px[x0 + x, y0 + y]): x += step
        return x
    hl, hr = edge(-1), edge(1)
    f = lambda v: round(v / height, 3)
    return {"h": height, "w/h": f(width), "visor y": f(y - top), "visor": f(vw), "head": f(hr - hl), "cheek L": f(vl - hl), "cheek R": f(hr - vr)}
for r, n in enumerate(names):
    if r * 512 >= im.height: break
    a, b = measure(0, r * 512), measure(512, r * 512)
    print(f"{n:9}", "  ".join(f"{k} {a[k]}/{b[k]}" for k in a))
