import os, numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright
cands = [
 ("Roboto",500,116.87,0.0066),
 ("Roboto",600,116.87,0.0057),
 ("Instrument Sans",500,114.38,-0.0080),
 ("Instrument Sans",550,114.38,-0.0100),
 ("Instrument Sans",600,114.38,-0.0115),
 ("Instrument Sans",650,114.38,-0.0125),
 ("Instrument Sans",700,114.38,-0.0140),
 ("Inter",600,114.38,-0.0163),
 ("Public Sans",600,114.38,-0.0087),
]
url = ("https://fonts.googleapis.com/css2?"
 + "&".join("family="+f.replace(" ","+")+":wght@400..700" for f in ["Roboto","Instrument Sans","Inter","Public Sans"]) + "&display=block")
mock = np.asarray(Image.open('mock.jpg').convert('L')).astype(np.float32)
with sync_playwright() as p:
    b = p.chromium.launch(args=["--force-color-profile=srgb","--font-render-hinting=none","--disable-lcd-text"])
    pg = b.new_page(viewport={"width":1536,"height":864}, device_scale_factor=1)
    res=[]
    for fam, wt, size, ls in cands:
        html = f"""<!doctype html><html><head><meta charset=utf-8>
<link rel=stylesheet href="{url}">
<style>
html,body{{margin:0;background:#f4f3ee}}
h1{{position:absolute;left:46px;top:232px;margin:0;
 font-family:'{fam}';font-weight:{wt};font-size:{size}px;line-height:112px;
 letter-spacing:{ls}em;color:#050505;width:944px;-webkit-font-smoothing:antialiased}}
</style></head><body><h1>Ethiopia Hambela Metad, Natural</h1></body></html>"""
        open('work/_ht.html','w').write(html)
        pg.goto('file://'+os.path.abspath('work/_ht.html'))
        pg.wait_for_function("document.fonts.status==='loaded'"); pg.wait_for_timeout(350)
        pg.screenshot(path='work/_ht.png')
        a = np.asarray(Image.open('work/_ht.png').convert('L')).astype(np.float32)
        # region line1 only, search dx,dy
        best=(1e9,0,0)
        for dy in range(-16,17):
            ren=np.roll(a,-dy,axis=0)
            for dx in range(-10,11):
                ren2=np.roll(ren,-dx,axis=1)
                m=np.abs(ren2[222:340,40:1000]-mock[222:340,40:1000]).mean()
                if m<best[0]: best=(m,dx,dy)
        res.append((best[0],fam,wt,size,ls,best[1],best[2]))
        print(f"{fam:16s} {wt} ls {ls:+.4f}  line1MAE {best[0]:6.3f} dx {best[1]:+d} dy {best[2]:+d}")
    print('--- sorted')
    for r in sorted(res): print(f"{r[0]:6.3f}  {r[1]} {r[2]}")
    b.close()
