"""Make the four addressed native-source crops and a detail of the adjacent sector."""
from pathlib import Path
from hashlib import sha256
from PIL import Image, ImageDraw, ImageFont
import json

out = Path(__file__).resolve().parent
root = Path('../../../resources/readers/provenance/source-b7f1ce9338da1cad.html')
page = root / '0122_68r.jpg'
image = Image.open(page)
positions = [
    ('f68r1 top', 'rayed rim', 'f68r1.5–.7', (215, 112, 390, 251)),
    ('f68r2 top', 'crescent', 'f68r2.6', (805, 157, 955, 309)),
    ('f68r1 bottom', 'crescent', 'f68r1.37', (221, 579, 379, 733)),
    ('f68r2 bottom', 'rayed rim', 'f68r2.31', (775, 569, 932, 722)),
]
fig = Image.new('RGB',(788,642),'#f6f3ee')
draw = ImageDraw.Draw(fig)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',18)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',14)
draw.text((12,8),'Beinecke MS 408 · f68r, adjoining panels on the same foldout',font=font,fill='#29241f')
for i,(name,form,locus,box) in enumerate(positions):
    x=12+(i%2)*390; y=43+(i//2)*297
    draw.text((x,y),f'{name}  ·  {form}  ·  {locus}',font=small,fill='#29241f')
    patch=image.crop(box)
    patch.thumbnail((363,270))
    w,h=patch.size
    scale=min(363/w,265/h)
    patch=patch.resize((round(w*scale),round(h*scale)),Image.Resampling.LANCZOS)
    fig.paste(patch,(x,y+22))
fig.save(out/'MEDALLIONS.jpg',quality=95)
crop=(1175,225,1560,525)
img=image.crop(crop);img.resize((770,600),Image.Resampling.LANCZOS).save(out/'views/0122-cluster-detail.jpg',quality=95)
info={'source':str(page),'canvas':'https://collections.library.yale.edu/manifests/oid/2002046/canvas/1006196','local_size':image.size,'source_sha256':sha256(page.read_bytes()).hexdigest(),'image_coordinates':'x,y from top left of the retained local JPEG; box right/bottom excluded','panels':[{'position':n,'observed_shape':f,'reference':l,'box':b} for n,f,l,b in positions],'f68r3_cluster_detail':crop,'scale_note':'Each crop was enlarged for legibility, preserving aspect ratio. Dots and colour remain part of the photographed object.'}
manifest=json.loads((root.parent/'manifest.json').read_text())
info['canvas']=manifest['items'][122]['id']
(out/'MEDALLION_CROPS.json').write_text(json.dumps(info,indent=2,ensure_ascii=False)+'\n')
