#!/usr/bin/env python3
"""Canvas-metric calibration: for each spec, solve font-size from a measured
height and letter-spacing from a measured ink width, and report the left bearing
so an ink x can be turned into a box position."""
import json
import os
import sys

from playwright.sync_api import sync_playwright

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CSS = "file://" + os.path.join(ROOT, "work/fonts_data.css")


def main(specs):
    page = os.path.join(ROOT, "work/_calib.html")
    open(page, "w").write(
        f'<!doctype html><html><head><link rel="stylesheet" href="{CSS}"></head><body>'
        + "".join(f'<span style="font-family:Inter;font-weight:{w}">Inter {w}</span>'
                  for w in (400, 500, 600, 700, 800, 900)) + '</body></html>')
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--font-render-hinting=none"])
        pg = b.new_page()
        pg.goto("file://" + page)
        pg.wait_for_timeout(1200)
        res = pg.evaluate("""async (specs) => {
          for (const w of [400, 500, 600, 700, 800, 900]) {
            await document.fonts.load(`${w} 100px Inter`);
          }
          await document.fonts.ready;
          const c = document.createElement('canvas').getContext('2d');
          const out = [];
          for (const s of specs) {
            // size from a measured capital height
            c.font = `${s.weight} 100px "${s.family}"`;
            const capRatio = c.measureText('H').actualBoundingBoxAscent / 100;
            const size = s.cap ? s.cap / capRatio : s.size;
            c.font = `${s.weight} ${size}px "${s.family}"`;
            const m = c.measureText(s.text);
            const g = m.actualBoundingBoxLeft + m.actualBoundingBoxRight;
            const n = [...s.text].length - 1;
            const track = n > 0 ? (s.inkw - g) / (n * size) : 0;
            out.push({name: s.name, size: Math.round(size * 100) / 100,
                      natural: Math.round(g * 100) / 100,
                      track: Math.round(track * 10000) / 10000,
                      left: Math.round(m.actualBoundingBoxLeft * 100) / 100,
                      right: Math.round(m.actualBoundingBoxRight * 100) / 100,
                      asc: Math.round(m.actualBoundingBoxAscent * 100) / 100,
                      desc: Math.round(m.actualBoundingBoxDescent * 100) / 100,
                      width: Math.round(m.width * 100) / 100});
          }
          return out;
        }""", specs)
        b.close()
    for r in res:
        print(f"{r['name']:16s} size {r['size']:7.2f}  natural {r['natural']:7.2f}  "
              f"track {r['track']:+7.4f}em  inkL {r['left']:+6.2f} inkR {r['right']:6.2f} "
              f"asc {r['asc']:6.2f} desc {r['desc']:6.2f} adv {r['width']:7.2f}")


if __name__ == "__main__":
    main(json.load(open(sys.argv[1])))
