"""The crop sheet: every hand and foot of every voice, the render beside the drawing at the same place, size and camera,
cut from the overlay sheet around the part's own box. python3 cropsheet.py sheet.png parts.json out.png"""
import json, sys
from PIL import Image, ImageDraw
sheet, parts, out = Image.open(sys.argv[1]).convert("RGB"), json.load(open(sys.argv[2])), sys.argv[3]
names = ["butler", "coach", "colleague", "homie", "squire"]
cell, pad = 150, 18
tiles = []
for row, voice in enumerate(names):
    for part in ("hand_right", "hand_left", "foot_right", "foot_left"):
        b = parts[voice]["parts"][part]
        side = max(b["w"], b["h"]) + 2 * pad
        cx, cy = b["x"] + b["w"] / 2, b["y"] + b["h"] / 2
        box = lambda x0: (int(x0 + cx - side / 2), int(row * 512 + cy - side / 2), int(x0 + cx + side / 2), int(row * 512 + cy + side / 2))
        tiles.append((f"{voice} {part.replace('_', ' ')}", sheet.crop(box(0)).resize((cell, cell)), sheet.crop(box(512)).resize((cell, cell))))
o = Image.new("RGB", (4 * (2 * cell + 12), 5 * (cell + 22)), "white")
d = ImageDraw.Draw(o)
for k, (label, a, b) in enumerate(tiles):
    x, y = (k % 4) * (2 * cell + 12), (k // 4) * (cell + 22)
    o.paste(a, (x, y + 18)); o.paste(b, (x + cell + 2, y + 18))
    d.text((x + 2, y + 3), f"{label}   render | drawing", fill=(40, 40, 60))
o.save(out)
