import json, sys
import numpy as np
from playwright.sync_api import sync_playwright

FONTS = sys.argv[1] if len(sys.argv)>1 else "Barlow Semi Condensed:800"
LINES = {
 'L1': ("LONDON NEW YORK", 136.0, [95,230,344,459,592,745,857,936,1114,1341,1447], [0,12]),
 'L2': ("SEOUL LOS ANGELES", 140.0, [92,177,309,417,548,638,766,897,1007,1114,1228,1312,1394], []),
}
fam,wt = FONTS.split(':')
url=("https://fonts.googleapis.com/css2?family="+fam.replace(' ','+')+":wght@"+wt+"&display=block")
html=f"""<!doctype html><html><head><meta charset=utf-8><link rel=stylesheet href="{url}"></head><body></body></html>"""
open('work/_fit.html','w').write(html)
with sync_playwright() as p:
    b=p.chromium.launch(args=["--force-color-profile=srgb"])
    pg=b.new_page()
    pg.goto('file://'+__import__('os').path.abspath('work/_fit.html'))
    pg.wait_for_function("document.fonts.status==='loaded'",timeout=60000)
    out=pg.evaluate("""async ([fam,wt,lines])=>{
      await document.fonts.load(`800 100px "${fam}"`);
      const cv=document.createElement('canvas'); const ctx=cv.getContext('2d');
      const ref=1000; ctx.font=`800 ${ref}px "${fam}"`;
      const res={};
      for (const [k,[text,cap,lefts,skip]] of Object.entries(lines)) {
        const chars=[...text];
        let acc=0; const ink=[];
        for (const ch of chars){ const m=ctx.measureText(ch); ink.push(-m.actualBoundingBoxLeft); acc+=m.width; }
        // cumulative origins
        let o=0; const origins=[];
        for (const ch of chars){ origins.push(o); o+=ctx.measureText(ch).width; }
        res[k]={origins, ink};
      }
      const m=ctx.measureText('H'); res.cap=m.actualBoundingBoxAscent/ref;
      return res;
    }""",[fam,wt,LINES])
    b.close()
print('cap ratio', out['cap'])
for k,(text,cap,lefts,skip) in LINES.items():
    origins=out[k]['origins']; ink=out[k]['ink']
    chars=list(text)
    # indices of observed chars
    order=[i for i,c in enumerate(chars) if c!=' ' and i not in skip]
    assert len(order)==len(lefts), (len(order),len(lefts),k)
    # model: pos = x0 + S*(origins[i] + (i)*t) - S*ink[i]
    # unknowns x0, S (with t=0 first)
    A=[];y=[]
    for j,i in enumerate(order):
        A.append([1.0, origins[i]-ink[i]]); y.append(lefts[j])
    A=np.array(A); y=np.array(y)
    sol,res_,_,_=np.linalg.lstsq(A,y,rcond=None)
    pred=A@sol
    print(k,'cap',cap,'size(no track)=',sol[1],'x0=',sol[0],'resid rms',np.sqrt(((pred-y)**2).mean()),'max',np.abs(pred-y).max())
    # now add tracking t: pos = x0 + S*(origins - ink) + S*t*i ; fit S,t,x0
    A2=[]; 
    for j,i in enumerate(order):
        A2.append([1.0, origins[i]-ink[i], i])
    A2=np.array(A2)
    sol2,*_=np.linalg.lstsq(A2,y,rcond=None)
    pred2=A2@sol2
    print('   with tracking: size',sol2[1],'x0',sol2[0],'t_em',sol2[2]/sol2[1],'rms',np.sqrt(((pred2-y)**2).mean()),'max',np.abs(pred2-y).max())
    print('   implied font size from cap:',cap/out['cap'])
