"""python outline_389.py BOOK_FILES OUTPUT_DIR. Compare a measured outline and a computed fill to the two blurred trees, with fixed directions and held-out branches."""
from pathlib import Path
import sys,json,numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter,binary_closing,binary_fill_holes,map_coordinates
from scipy.optimize import minimize
from emblem_379 import coef,rnd
B55=(620,1430,1800,2630);B32=(640,2020,1770,3200);POST=(190,305,365,471)
def scale(a,sh):return np.asarray(Image.fromarray(a.astype(np.float32)).resize((sh,sh),Image.Resampling.BOX),float)
def native(d):return (255-np.asarray(Image.open(d/'72.jpg').convert('L').crop(B55))).astype(float)
def outline(a,mode,level):
 # Fixed bounds taken from all native pixels with darkness >10 (no alignment to destination).
 y,x=np.where(a>10);box=(slice(y.min(),y.max()+1),slice(x.min(),x.max()+1))
 v=a/64 if mode=='raw' else binary_fill_holes(binary_closing(a>level,iterations=1))
 return np.pad(scale(v[box],200),34)
def project(ref,p,x,y,mir=False):
 cx,cy,w,h=p;return map_coordinates(ref,[133.5+(y-cy)*200/h,133.5+(x-cx)*200/w*(-1 if mir else 1)],order=1,mode='constant',prefilter=False)
def main(d,o):
 a=native(d);p32=(255-np.asarray(Image.open(d/'49.jpg').convert('L').crop(B32))).astype(float);poster=np.asarray(Image.open(d/'notice_2016_363.jpg').convert('L').crop(POST),float)
 data={'p32':scale(p32,165),'poster':scale(poster,165)}
 modes={k:outline(a,v,t) for k,v,t in [('raw','raw',0),('fill3','fill',3),('fill9','fill',9),('fill15','fill',15),('fill25','fill',25)]}
 y,x=np.indices((165,165));allm=x>=0;splits={'all':allm,'even16':(y//16)%2==0,'odd16':(y//16)%2==1,'left':x<82,'right':x>=82};results={}
 def f(dst,mode,train,mir=False):
  ss=train&(y%3==1)&(x%3==1);xx=x[ss];yy=y[ss];target=dst[ss];best=None
  for sig in (0,3,7,12,19,29):
   ref=gaussian_filter(modes[mode],sig) if sig else modes[mode]
   def fun(p):return -coef(project(ref,p,xx,yy,mir),target)
   seed=[81,89,117,125]
   g=minimize(fun,seed,method='Nelder-Mead',bounds=[(58,106),(58,115),(70,156),(72,160)],options={'initial_simplex':np.vstack((seed,seed+np.diag([5,5,7,7]))),'maxiter':240,'xatol':.025,'fatol':.000001})
   if best is None or g.fun<best[0]:best=(g.fun,g.x,sig,ref)
  _,p,sig,ref=best;z=project(ref,p,x,y,mir);test=~train if not train.all() else train
  return {'r_all':rnd(coef(dst.ravel(),z.ravel())),'fit':rnd(coef(dst[train],z[train])),'held':rnd(coef(dst[test],z[test])),'sig':sig,'p':list(map(rnd,p))}
 for n,dst in data.items():
  rr=results[n]={}
  for k in modes:rr[k]=f(dst,k,allm)
  for tag,train in splits.items():
   if tag!='all':rr['fill9_'+tag]=f(dst,'fill9',train)
  rr['fill9_mirror']=f(dst,'fill9',allm,True);v=rr['fill9'];pr=project(gaussian_filter(modes['fill9'],v['sig']),v['p'],x,y)
  # Restrict to crown, then remove shared coarse envelope with the same high-pass filter.
  mask=(y<v['p'][1])&(x>v['p'][0]-.47*v['p'][2])&(x<v['p'][0]+.47*v['p'][2])&(y>v['p'][1]-.50*v['p'][3]);rr['crown']={}
  for sig in [4,8,16]:
   u=dst-gaussian_filter(dst,sig);v1=pr-gaussian_filter(pr,sig);rr['crown'][f'highpass{sig}']=rnd(coef(u[mask],v1[mask]))
  rr['crown']['raw_r']=rnd(coef(dst[mask],pr[mask]))
  for tag,v in [('raw',rr['raw']),('fill9',rr['fill9'])]:
   lookup=modes[tag];p=v['p'];ref=lookup;rr[tag]['without_smoothing_fixed_geometry']=rnd(coef(project(ref,p,x,y).ravel(),dst.ravel()))
 result={'sources':{'72':B55,'49':B32,'poster':POST},'outline_range':[int(a.min()),int(a.max())],'native_outline_fraction_gt9':float((a>9).mean()),'filled_native_fraction_at9':float(binary_fill_holes(binary_closing(a>9,iterations=1)).mean()),'results':results}
 (o/'outline_389_results.json').write_text(json.dumps(result,indent=2)+'\n')
 for n,rr in results.items():print(n,[(k,v.get('r_all'),v.get('held'),v.get('sig')) for k,v in rr.items() if k!='crown'],rr['crown'],flush=True)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
