import sys, io
from PIL import Image
import numpy as np
from playwright.sync_api import sync_playwright

FONTS = sys.argv[1].split(",")
TEXT = "Considered"
CAP = 89.0
WANT = 549.0
fams = "&".join("family=" + f.replace(" ", "+") + ":wght@300;400;500;600" for f in FONTS)
html = ("<!doctype html><html><head><meta charset='utf-8'>"
        f"<link rel='stylesheet' href='https://fonts.googleapis.com/css2?{fams}&display=block'>"
        "<style>html,body{margin:0;background:#efe4d2} .r{white-space:nowrap;display:inline-block;line-height:1;color:#1f1c17}</style>"
        "</head><body></body></html>")
open("work/sheet.html","w").write(html)
with sync_playwright() as p:
    b=p.chromium.launch(channel="chrome")
    pg=b.new_page(viewport={"width":1200,"height":900}, device_scale_factor=1)
    pg.goto("file:///home/ubuntu/standalone/builds/25-aesop-1/work/sheet.html")
    pg.wait_for_function("document.fonts.status === 'loaded'", timeout=60000)
    rows=[]
    for f in FONTS:
        pg.evaluate("""async (f) => { await document.fonts.load(`400 100px "${f}"`);
            const d=document.createElement('div'); d.className='r'; d.id='t';
            d.textContent='Considered'; document.body.appendChild(d); }""", f)
        m = pg.evaluate("""(f) => { const cv=document.createElement('canvas');
            const ctx=cv.getContext('2d'); ctx.font=`400 100px "${f}"`;
            const cap=ctx.measureText('H').actualBoundingBoxAscent;
            const w=ctx.measureText('Considered').width;
            return {cap, w}; }""", f)
        size = CAP/(m['cap']/100.0)
        # solve tracking to hit WANT with ink width approx (advance-based)
        track = (WANT - m['w']*size/100.0)/9/size
        pg.evaluate("""([f,size,track]) => { const d=document.getElementById('t');
            d.style.fontFamily=`"${f}"`; d.style.fontSize=size+'px';
            d.style.letterSpacing=track+'em'; }""", [f,size,track])
        el=pg.query_selector('#t')
        buf=el.screenshot()
        im=Image.open(io.BytesIO(buf)).convert('RGB')
        rows.append((f,im))
        pg.evaluate("() => document.getElementById('t').remove()")
    b.close()

mock=Image.open('mock.jpg').convert('RGB').crop((55,150,700,265))
H=sum(r[1].size[1] for r in rows)+mock.size[1]+12*len(rows)+10
W=max([mock.size[0]]+[r[1].size[0] for r in rows])+20
out=Image.new('RGB',(W,H),(239,228,210))
y=0; out.paste(mock,(0,0)); y=mock.size[1]+10
from PIL import ImageDraw
d=ImageDraw.Draw(out)
for f,im in rows:
    d.text((2,y-2),f,fill=(120,60,60))
    out.paste(im,(0,y+10)); y+=im.size[1]+12
out.save('work/sheet.png')
print('ok', W, H)
