import os, sys, numpy as np
from playwright.sync_api import sync_playwright
FONTS=sys.argv[1]
fam,wt=FONTS.split(':')
LINES={
 'L1': ("LONDON NEW YORK", [95,230,344,459,592,745,857,936,1114,1341,1447], [0,12]),
 'L2': ("SEOUL LOS ANGELES", [92,177,309,417,548,638,766,897,1007,1114,1228,1312,1394], []),
}
url=("https://fonts.googleapis.com/css2?family="+fam.replace(' ','+')+":wght@"+wt+"&display=block")
open('work/_fit.html','w').write(f'<!doctype html><html><head><meta charset=utf-8><link rel=stylesheet href="{url}"></head><body></body></html>')
with sync_playwright() as p:
    b=p.chromium.launch(args=["--force-color-profile=srgb"]); pg=b.new_page()
    pg.goto('file://'+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}"`); await document.fonts.ready;
      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]] of Object.entries(lines)) {
        let o=0; const origins=[], inks=[];
        for (const ch of text){ const m=ctx.measureText(ch); origins.push(o); inks.push(m.actualBoundingBoxLeft); o+=m.width; }
        const fm=ctx.measureText(text);
        res[k]={origins,inks,full:fm.width,strLeft:fm.actualBoundingBoxLeft,strRight:fm.actualBoundingBoxRight};
      }
      res.cap=ctx.measureText('H').actualBoundingBoxAscent/ref;
      return res;}""",[fam,wt,LINES])
    b.close()
for k,(text,lefts,skip) in LINES.items():
    origins=out[k]['origins']; inks=out[k]['inks']; chars=list(text)
    order=[i for i,c in enumerate(chars) if c!=' ' and i not in skip]
    A=[];y=[]
    for j,i in enumerate(order):
        A.append([1.0,(origins[i]-inks[i])/1000.0]); y.append(lefts[j])
    A=np.array(A);y=np.array(y)
    sol,*_=np.linalg.lstsq(A,y,rcond=None)
    pred=A@sol
    print(k, 'size',round(sol[1],2),'x0',round(sol[0],2),'rms',round(np.sqrt(((pred-y)**2).mean()),2))
    print('   ', ' '.join(f"{chars[i]}:{int(lefts[j])}/{pred[j]:.0f}" for j,i in enumerate(order)))
