import json
from playwright.sync_api import sync_playwright
SPECS = [
 ("Prata",400,80.00,-0.0297,"Prata"),
 ("Tinos",400,99.05,-0.0459,"Tinos:wght@400"),
 ("Gilda Display",400,92.44,-0.0560,"Gilda+Display"),
 ("Noto Serif",500,90.43,-0.0913,"Noto+Serif:wght@500"),
 ("Newsreader",500,94.55,-0.0532,"Newsreader:wght@500"),
 ("Libre Caslon Text",400,83.20,-0.0433,"Libre+Caslon+Text"),
 ("Playfair Display",400,83.39,-0.0206,"Playfair+Display:wght@400"),
 ("Spectral",400,94.90,-0.0649,"Spectral:wght@400"),
 ("Nimbus Roman",400,96.0,-0.04,""),
 ("Merriweather",400,76.44,-0.0099,"Merriweather:wght@400"),
]
LINES=["The world’s largest","independent design","consultancy is 24 partners."]
params=[spec[4] for spec in SPECS if spec[4]]
css="https://fonts.googleapis.com/css2?"+"&".join("family="+x for x in params)+"&display=block"
with sync_playwright() as p:
    b=p.chromium.launch(args=["--force-color-profile=srgb","--font-render-hinting=none","--disable-lcd-text","--disable-gpu"])
    pg=b.new_page(viewport={"width":1400,"height":400},device_scale_factor=1)
    pg.set_content(f'<link rel=stylesheet href="{css}"><style>body{{margin:0;background:#1a1a1a;color:#fff}} span{{white-space:nowrap;line-height:1;display:inline-block}}</style><div id=box></div>')
    pg.wait_for_timeout(2500)
    print('fonts status', pg.evaluate("document.fonts.status"))
    for fam,wt,size,track,_ in SPECS:
        ok=pg.evaluate("async ([f,w])=>{await document.fonts.load(`${w} 100px \"${f}\"`);return document.fonts.check(`${w} 100px \"${f}\"`)}",[fam,str(wt)])
        ws=[]
        for line in LINES:
            pg.evaluate("""([line,fam,wt,size,track])=>{const s=document.createElement('span');s.textContent=line;s.style.fontFamily=`"${fam}"`;s.style.fontWeight=wt;s.style.fontSize=size+'px';s.style.letterSpacing=track+'em';const b=document.getElementById('box');b.innerHTML='';b.appendChild(s);}""",[line,fam,wt,size,track])
            w=pg.evaluate("()=>document.querySelector('#box span').getBoundingClientRect().width")
            ws.append(round(w,1))
        errs=[round(ws[i]-t,1) for i,t in enumerate([681,716,950])]
        print(f"{fam:20s} ok={ok} {ws} err {errs} sumabs {sum(abs(e) for e in errs):.1f}")
    b.close()
