"""python figure_392.py BOOK_FILES REFERENCE_DIR OUTPUT_DIR. Figures show measured source pixels; adjustments are labelled."""
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont,ImageOps
import json,numpy as np,sys
from scipy.ndimage import gaussian_filter
from emblem_379 import masks,getref,pred
from outline_389 import B55,B32,POST,native,outline
def main(d,s,o):
 FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans';font=lambda n,b=False:ImageFont.truetype(FONT+('-Bold' if b else '')+'.ttf',n)
 def base(w,h,head,sub):
  c=Image.new('RGB',(w,h),'#f6f4ed');p=ImageDraw.Draw(c);p.text((24,14),head,fill='#143a37',font=font(26,1));p.text((24,55),sub,fill='#3d534f',font=font(15));return c,p
 def pic(c,img,box,bg='white'):
  x,y,w,h=box;p=ImageDraw.Draw(c);p.rectangle([x,y,x+w-1,y+h-1],fill=bg);im=ImageOps.contain(img,(w,h),Image.Resampling.LANCZOS);c.paste(im,(x+(w-im.width)//2,y+(h-im.height)//2))
 def txt(p,x,y,t,size=15,b=False):p.text((x,y),t,fill='#183a36',font=font(size,b))
 def gray(a):return Image.fromarray(np.uint8(np.clip(a,0,255)))
 pp=Image.open(d/'notice_2016_363.jpg').convert('L');book=Image.open(d/'72.jpg').convert('L');p32=Image.open(d/'49.jpg').convert('L');ref,_=getref(Image.open(s/'countdown.jpg'));sc=json.loads((o/'emblem_379_results.json').read_text());p=sc['strict_refits']['blocks_and_dilate4']['p'];obs=np.array(pp.crop((162,113,388,236)),float);mask=masks(obs)['blocks_and_dilate4'];y,x=np.indices(obs.shape);z=pred(ref,p,x+162,y+113);a=gray(255-np.maximum(0,obs-1)*18).convert('RGB');ar=np.asarray(a).copy();ar[~mask]=[116,150,147];a=Image.fromarray(ar)
 c,dr=base(870,392,'What survives behind the lettering?','Left to right: clean archived source, exposed poster pixels, and the fitted source under the same exclusions.')
 for j,(title,img) in enumerate([('2012 countdown',gray(255-255*z)),('2016 notice',a),('2012 under poster mask',None)]):
  x0=24+280*j
  if img is None:
   ar=np.array(gray(255-255*z).convert('RGB'));ar[~mask]=[116,150,147];img=Image.fromarray(ar)
  txt(dr,x0,98,title,17,1);pic(c,img,(x0,135,260,160))
 txt(dr,24,319,'Teal = excluded. The poster’s faint gray levels are amplified for display.',16)
 txt(dr,24,348,'No letter-covered detail was reconstructed. The clean reference is scaled to the poster.',15)
 c.save(o/'emblem_views_379.png',optimize=True)
 c,dr=base(890,730,'The same two motifs, in opposite order','These columns preserve vertical order. Panel size and spacing are for comparison; they are not to scale.')
 txt(dr,35,96,'JANUARY 2016 NOTICE',17,1);txt(dr,475,96,'LIBER PRIMUS · PAGE 55',17,1)
 pic(c,a,(35,135,375,179));txt(dr,35,326,'Emblem behind lettering',16,1);txt(dr,35,350,'Contrast raised; teal marks excluded pixels.',14)
 tree55=gray(255-4.0*native(d));pic(c,tree55,(475,132,375,190));txt(dr,475,326,'Pale outline tree',16,1);txt(dr,475,350,'Book ink contrast raised ×4.',14)
 pt=np.array(pp.crop(POST),float);pic(c,gray(255-22*(pt-1)),(35,390,375,212));txt(dr,35,620,'Faint tree below the emblem',16,1);txt(dr,35,644,'Poster brightness inverted and amplified.',14)
 pic(c,book.crop((690,2755,1840,3190)),(475,390,375,212));txt(dr,475,620,'Spread-wing emblem below the tree',16,1);txt(dr,475,644,'Book artwork, original polarity.',14)
 txt(dr,35,695,'Page 55 is archive 72.jpg. Page 32 (49.jpg) contains the blurred tree, a separate comparison.',15)
 c.save(o/'pair_views_392.png',optimize=True)
 c,dr=base(906,414,'Which tree drawing fits the surviving pixels?','The first panel is a researcher’s candidate source. The remaining three are archive crops.')
 donor=Image.open(s/'originalTreeImage.jpg').convert('L');r,_=getref(donor);r=r[4:-4,4:-4][:,::-1];im1=gray(255-255*r);a32=255-np.array(p32.crop(B32));yy,xx=np.where(a32>65);im2=gray(255-a32[yy.min():yy.max()+1,xx.min():xx.max()+1]);ta=native(d);yy,xx=np.where(ta>10);im3=gray(255-4*ta[yy.min():yy.max()+1,xx.min():xx.max()+1]);im4=gray(255-22*(pt-1))
 for j,(title,img,desc) in enumerate([('Candidate source',im1,'Mirrored horizontally'),('LP2 page 32',im2,'Original blurred ink'),('2016 notice',im4,'Contrast amplified'),('LP2 page 55',im3,'Pale line amplified')]):
  x=22+221*j;txt(dr,x,100,title,17,1);pic(c,img,(x,140,198,197));txt(dr,x,352,desc,13)
 txt(dr,22,385,'Crops are scaled separately to compare branching, not physical size. Source candidate: MonokumaBear repository.',14)
 c.save(o/'tree_sources_394.png',optimize=True)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
