"""Make the compact inspection plate for the first baseline report."""
import base64
from io import BytesIO
import json
from pathlib import Path
import re

from PIL import Image, ImageDraw, ImageFont

RESULTS = Path(__file__).resolve().parent.parent / "results"
text = (RESULTS / "field-review.html").read_text()
slides = json.loads(re.search(r'<script type="application/json" id="data">(.*?)</script>', text, re.S)[1])
scans = {s["name"].split("_")[0]: s for s in slides}

def decode(b64):
    return Image.open(BytesIO(base64.b64decode(b64))).convert("RGBA")

def font(size, bold=False, serif=False):
    family="DejaVuSerif" if serif else "DejaVuSans"
    name=family+("-Bold" if bold else "")+".ttf"
    return ImageFont.truetype(name,size)

page=Image.new("RGB",(1344,955),"#f8f8f2")
draw=ImageDraw.Draw(page)
ink="#192f31"
def label(at, value, size, **kw):
    draw.text(at,value,font=font(size,**kw),fill=ink)

draw.rectangle((35,25,1308,29),fill=ink)
label((36,41),"Patrick Center microscopy pilot",20)
label((33,72),"Which objects get an outline?",48,serif=True)
label((36,141),"Three examples from the dark-rim detector. The upper and lower rows show the same focal plane.",21)
cases=[
    ("GC104890a",8,(111,76,351,240),"Banded oval","The rim is largely intact.","Mask overlap with visual trace: 0.91."),
    ("GC104890a",8,(38,553,278,717),"Second oval in the same field","The right margin is interrupted.","The detector missed this outline."),
    ("GC104887a",8,(498,484,738,648),"Angular particle","A compact outline fits this dark speck.","Its shape gives little evidence of a valve."),
]
for j,(name,number,box,title,note1,note2) in enumerate(cases):
    x=36+431*j
    s=scans[name]
    f=s["fields"][number-1]
    raw=decode(f["images"][f["z"]])
    overlay=decode(f["variants"]["dark"]["overlay"])
    result=Image.alpha_composite(raw,overlay)
    label((x,190),title,22,bold=True)
    label((x,223),f"{name}  ·  field {number}  ·  plane {f['z']+1}",17)
    for y,img,row in [(259,raw,"Field"),(562,result,"Outlines")]:
        w,h=413,282
        patch=img.crop(box).resize((w,h),Image.Resampling.LANCZOS)
        page.paste(patch,(x,y))
        draw.rectangle((x,y,x+82,y+28),fill=ink)
        draw.text((x+7,y+3),row,font=font(16),fill="white")
        bar=round((5/s['sx'])*w/(box[2]-box[0]))
        draw.rectangle((x+7,y+h-37,x+bar+21,y+h-6),fill="#283536")
        draw.text((x+14,y+h-36),"5 µm",font=font(14),fill="white")
        draw.rectangle((x+14,y+h-16,x+14+bar-1,y+h-13),fill="white")
    label((x,858),note1,17)
    label((x,886),note2,17)
draw.line((36,927,1308,927),fill="#aebbb1")
page.save(RESULTS / "segmentation-examples.png")
