import sys
from playwright.sync_api import sync_playwright
FAM = sys.argv[1]; AXIS=sys.argv[2]; LO=sys.argv[3]; HI=sys.argv[4]; VALS=sys.argv[5]
TEXT=["Considered","formulations,","made in Melbourne."]; WANT=[549.0,638.0,873.0]; CAP=89.0
url=f"https://fonts.googleapis.com/css2?family={FAM.replace(' ','+')}:{AXIS},wght@{LO}..{HI},400&display=block"
html=("<!doctype html><html><head><meta charset='utf-8'>"
      f"<link rel='stylesheet' href='{url}'></head><body></body></html>")
open("work/opsz.html","w").write(html)
with sync_playwright() as p:
    b=p.chromium.launch(channel="chrome")
    pg=b.new_page(viewport={"width":1600,"height":900})
    pg.goto("file:///home/ubuntu/standalone/builds/25-aesop-1/work/opsz.html")
    pg.wait_for_function("document.fonts.status === 'loaded'", timeout=60000)
    for v in [float(x) for x in VALS.split(",")]:
        r=pg.evaluate("""async ([fam,v,texts]) => {
          await document.fonts.load(`400 100px "${fam}"`);
          const d=document.createElement('div');
          d.style.cssText=`position:absolute;white-space:nowrap;line-height:1;font-family:"${fam}";font-size:100px;font-weight:400;font-variation-settings:"${'opsz'}" ${v}`;
          document.body.appendChild(d);
          const out={};
          for (const t of texts) { d.textContent=t; out[t]=d.getBoundingClientRect().width; }
          d.remove();
          const ctx2=document.createElement('canvas').getContext('2d');
          ctx2.font=`400 100px "${fam}"`;
          return {out, cap: ctx2.measureText('H').actualBoundingBoxAscent};
        }""",[FAM,v,TEXT])
        size=CAP/(r['cap']/100.0)
        ws=[r['out'][t]*size/100 for t in TEXT]
        print(f"opsz {v:5.0f} size {size:6.2f} " + " ".join(f"{w:6.1f}({w-W:+5.1f})" for w,W in zip(ws,WANT)))
    b.close()
