"""Produce a focal-difference inspection plate from the existing practice fields."""
import base64
import json
import re
from io import BytesIO
from pathlib import Path

from PIL import Image, ImageChops, ImageDraw, ImageFont, ImageOps

root = Path(__file__).resolve().parent.parent
html = (root / "results/practice-round-1.html").read_text()
frames = json.loads(re.search(r'id="frames">(.*?)</script>', html, re.S)[1])
font = ImageFont.truetype("DejaVuSans.ttf", 17)
plate = Image.new("RGB", (1200, len(frames) * 325), "white")
draw = ImageDraw.Draw(plate)
for row, frame in enumerate(frames):
    planes = [Image.open(BytesIO(base64.b64decode(p))).convert("L") for p in frame["images"]]
    z = max(1, min(frame["z"], len(planes)-2))
    # Display planes have a shared contrast curve but are JPEG-compressed.
    a, middle, b = planes[z-1:z+2]
    signed = ImageChops.add(ImageChops.subtract(b, a, 2, 128), Image.new("L", a.size), 1, 0)
    absolute = ImageOps.autocontrast(ImageChops.difference(b, a))
    for col, (image, title) in enumerate(((middle, f"Plane {z+1}"), (signed, "Signed difference"), (absolute, "Absolute difference, stretched"))):
        x, y = col*400, row*325
        draw.text((x+5, y+3), f"{frame['slide'][:9]} field {frame['number']}  {title}", fill="black", font=font)
        plate.paste(image.resize((298, 298), Image.Resampling.LANCZOS), (x+5, y+25))
plate.save(root / "results/l1/focus-differences.jpg", quality=92)
