import os, numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright
cands=["IBM Plex Mono","Source Code Pro","Fira Mono","Space Mono","Chivo Mono","Geist Mono","Azeret Mono","Red Hat Mono","Sometype Mono","Roboto Mono","JetBrains Mono","Noto Sans Mono"]
url="https://fonts.googleapis.com/css2?" + "&".join("family="+f.replace(" ","+")+":wght@400;500" for f in cands) + "&display=block"
TEXT="03 • BLUEBERRY • HONEY • LAVENDER"
mock=np.asarray(Image.open('mock.jpg').convert('L')).astype(np.float32)
# target region generous around the line
X0,Y0,X1,Y1=35,766,560,796
mt=mock[Y0:Y1,X0:X1]
mtarget=rund=None
def inkbox(a,t=128):
    m=a<t; ys,xs=np.where(m)
    if not len(ys): return None
    return xs.min(),ys.min(),xs.max(),ys.max()
mbi=inkbox(mt)
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":700,"height":120},device_scale_factor=1)
    res=[]
    for fam in cands:
        best=(1e9,None)
        for size in (21.6,22.0,22.3,22.6,23.0):
            for ls in (0.05,0.07,0.084,0.10,0.12):
                html=f"""<!doctype html><html><head><meta charset=utf-8><link rel=stylesheet href="{url}">
<style>html,body{{margin:0;background:#f4f3ee}} .t{{position:absolute;left:20px;top:20px;font-family:'{fam}';font-weight:400;font-size:{size}px;line-height:1;letter-spacing:{ls}em;color:#050505;white-space:nowrap;-webkit-font-smoothing:antialiased}}</style>
</head><body><div class=t>{TEXT}</div></body></html>"""
                pg.set_content(html)
                pg.wait_for_function("document.fonts.status==='loaded'")
                pg.wait_for_timeout(60)
                pg.screenshot(path='work/_mf.png')
                a=np.asarray(Image.open('work/_mf.png').convert('L')).astype(np.float32)
                ib=inkbox(a)
                if ib is None: continue
                w=ib[2]-ib[0]+1
                # place into target region by translating so ink x0 aligns to mock x0, y0 to mock y0
                canvas=np.full((Y1-Y0,X1-X0),244,np.float32)
                dx=43-(ib[0]-0)  # we'll paste using absolute offset: shift candidate ink to x=43-35=8 rel
                # build canvas by pasting candidate at (rel_x, rel_y)
                cx = 43-X0 - ib[0]
                cy = 773-Y0 - ib[1]
                # extract candidate ink area with margin
                sx0=max(0,ib[0]-4); sy0=max(0,ib[1]-4); sx1=min(a.shape[1],ib[2]+5); sy1=min(a.shape[0],ib[3]+5)
                sub=a[sy0:sy1, sx0:sx1]
                px=cx+(sx0-ib[0]); py=cy+(sy0-ib[1])
                # clamp
                x0=max(0,px); y0=max(0,py); x1=min(X1-X0,x0+sub.shape[1]-(x0-px)); y1=min(Y1-Y0,y0+sub.shape[0]-(y0-py))
                canvas[y0:y1,x0:x1]=sub[(y0-py):(y0-py)+(y1-y0),(x0-px):(x0-px)+(x1-x0)]
                # search small offsets
                bestlocal=1e9
                for oy in range(-5,6):
                    for ox in range(-5,6):
                        cc=np.roll(np.roll(canvas,oy,axis=0),ox,axis=1)
                        v=np.abs(cc-mt).mean()
                        if v<bestlocal: bestlocal=v
                if bestlocal<best[0]: best=(bestlocal,(size,ls,w))
        res.append((best[0],fam,best[1]))
        print(f"{fam:16s} MAE {best[0]:6.2f} size/ls {best[1][0]} {best[1][1]:+.3f} w {best[1][2]}")
    print('---')
    for r in sorted(res): print(f"{r[0]:6.2f} {r[1]}")
    b.close()
