import json
from playwright.sync_api import sync_playwright

FONTS = [("Playfair Display", 500), ("Playfair Display", 600), ("Bodoni Moda", 500),
         ("Prata", 400), ("DM Serif Display", 400), ("Newsreader", 500),
         ("Spectral", 500), ("Libre Caslon Display", 400), ("Lora", 500),
         ("Merriweather", 400), ("Source Serif 4", 500), ("Petrona", 500),
         ("Fraunces", 500), ("Literata", 500), ("Noto Serif Display", 500),
         ("Roboto Serif", 500), ("Bitter", 500), ("Crimson Pro", 500)]

fam = "&".join("family=" + f.replace(" ", "+") +
               ":wght@" + str(w) for f, w in FONTS)
url = "https://fonts.googleapis.com/css2?" + fam + "&display=block"

rows = "".join(
    f'<div class="r" data-f="{f}" data-w="{w}"><span class="t"></span></div>'
    for f, w in FONTS)
html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{url}">
<style>html,body{{margin:0}} .r{{white-space:nowrap;line-height:1}}
.t{{display:inline-block;line-height:1;font-size:125.2px}}</style>
</head><body>{rows}</body></html>"""
open("work/_ratio.html", "w").write(html)

with sync_playwright() as p:
    b = p.chromium.launch()
    pg = b.new_page(viewport={"width": 2400, "height": 800})
    pg.goto("file:///home/ubuntu/standalone/builds/23-tate-2/work/_ratio.html")
    pg.wait_for_function("document.fonts.status === 'loaded'", timeout=120000)
    pg.wait_for_timeout(1500)
    out = pg.evaluate("""async (fonts) => {
      const res = [];
      for (const [f,w] of fonts) {
        await document.fonts.load(`${w} 125px "${f}"`);
      }
      await document.fonts.ready;
      const cv = document.createElement('canvas');
      const ctx = cv.getContext('2d');
      for (const [f,w] of fonts) {
        ctx.font = `${w} 125.2px "${f}"`;
        const a = ctx.measureText('Vanessa Bell and');
        const b2 = ctx.measureText('Duncan Grant');
        const cap = ctx.measureText('H');
        res.push([f, w, a.actualBoundingBoxLeft + a.actualBoundingBoxRight,
                  b2.actualBoundingBoxLeft + b2.actualBoundingBoxRight,
                  cap.actualBoundingBoxAscent,
                  a.width, b2.width]);
      }
      return res;
    }""", FONTS)
    b.close()

print(f"{'family':24s} {'wt':>4s} {'ink1':>6s} {'ink2':>6s} {'ratio':>6s} {'cap':>6s} {'size90':>7s} {'trk1':>7s} {'trk2':>7s}")
for f, w, i1, i2, cap, w1, w2 in out:
    size = 90 / (cap / 125.2)
    # tracking needed to hit mock ink widths 903 / 792
    t1 = (903 - i1) / 15 / size
    t2 = (792 - i2) / 11 / size
    print(f"{f:24s} {w:4d} {i1:6.0f} {i2:6.0f} {i2/i1:6.3f} {cap:6.1f} {size:7.1f} {t1:+7.4f} {t2:+7.4f}")
