import json, sys
from playwright.sync_api import sync_playwright

URL = ("https://fonts.googleapis.com/css2?family=Inter+Tight:wght@100..900"
       "&family=Libre+Baskerville:wght@400;700&family=Lora:wght@400..700&display=block")
strings = {
 "eyebrow": "TATE BRITAIN · LONDON",
 "nav_whatson": "WHAT'S ON", "nav_visit": "VISIT", "nav_art": "ART",
 "nav_learn": "LEARN", "nav_shop": "SHOP",
 "skip": "Skip navigation",
 "sub": "Two painters, one house, a whole way of living. Until 5 April 2026. Free for Members.",
 "book": "Book now", "seeall": "See all exhibitions",
 "foot1": "Free admission at Tate Britain, Tate Modern and Tate Liverpool",
 "foot2": "Members go free exhibitions",
 "label1": "TATE BRITAIN", "label2": "TATE MODERN", "label3": "TATE LIVERPOOL", "label4": "TATE ST IVES",
 "head1": "Vanessa Bell and", "head2": "Duncan Grant:", "head3": "Inside Bloomsbury",
}
html = """<html><head><link rel=stylesheet href='%s'>
<style>body{margin:0}canvas{display:block}</style></head><body><canvas id=c width=2000 height=400></canvas></body></html>""" % URL
with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none","--disable-lcd-text"])
    pg = b.new_page(viewport={"width":2000,"height":400})
    pg.set_content(html)
    pg.evaluate("""async () => {
      for (const spec of ['400 100px \"Inter Tight\"','400 100px \"Libre Baskerville\"','400 100px \"Lora\"']) {
        try { await document.fonts.load(spec, 'ABCabc'); } catch(e) {}
      }
      await document.fonts.ready;
    }""")
    pg.wait_for_timeout(500)
    print('check', pg.evaluate("() => [document.fonts.check('400 100px \"Inter Tight\"'), document.fonts.check('400 100px \"Libre Baskerville\"'), document.fonts.check('400 100px \"Lora\"')]"))
    res = pg.evaluate("""(args) => {
      const [strings, fams] = args;
      const c = document.getElementById('c'); const x = c.getContext('2d');
      const out = {};
      for (const fam of fams) {
        out[fam] = {};
        for (const [k,s] of Object.entries(strings)) {
          x.font = '400 100px "'+fam+'"';
          const m = x.measureText(s);
          out[fam][k] = {ink: m.actualBoundingBoxLeft + m.actualBoundingBoxRight,
                         adv: m.width, asc: m.actualBoundingBoxAscent, desc: m.actualBoundingBoxDescent};
        }
        x.font = '400 100px "'+fam+'"';
        const H = x.measureText('H');
        out[fam].cap = H.actualBoundingBoxAscent;
        const o = x.measureText('o');
        out[fam].xh = o.actualBoundingBoxAscent;
        const Hd = x.measureText('Hd');
        out[fam].asc = Hd.actualBoundingBoxAscent;
      }
      return out;
    }""", [strings, ["Inter Tight", "Libre Baskerville", "Lora"]])
    print(json.dumps(res, indent=1))
    b.close()
