import json, os, sys
from playwright.sync_api import sync_playwright

root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with sync_playwright() as p:
    b = p.chromium.launch(args=["--force-color-profile=srgb",
                                "--font-render-hinting=none",
                                "--disable-lcd-text", "--disable-gpu"])
    pg = b.new_page(viewport={"width": 1536, "height": 864}, device_scale_factor=1)
    pg.goto("file://" + os.path.join(root, "src/index.html"))
    pg.wait_for_timeout(600)
    try:
        pg.evaluate("document.fonts.ready")
    except Exception:
        pass
    pg.wait_for_timeout(300)
    out = pg.evaluate("""() => {
      const res = {body: document.body.getBoundingClientRect().toJSON()};
      const sel = ['.logo','.nav','.eyebrow','.headline','.sub','.actions','.btn','.link','.facts'];
      for (const s of sel) {
        const e = document.querySelector(s);
        if (!e) continue;
        const cs = getComputedStyle(e);
        res[s] = {rect: e.getBoundingClientRect().toJSON(),
                  font: cs.fontFamily, size: cs.fontSize, lh: cs.lineHeight,
                  ls: cs.letterSpacing, weight: cs.fontWeight};
      }
      const h = document.querySelector('.headline');
      const node = [...h.childNodes].find(n => n.nodeType === 3);
      const range = document.createRange();
      range.selectNodeContents(h);
      res.headlineLines = [...range.getClientRects()].map(r => r.toJSON());
      res.headlineTextRects = [];
      if (node) {
        let text = node.textContent;
        // per-character rects grouped into visual lines
        let lastY = null, groups = [];
        for (let i = 0; i < text.length; i++) {
          const rr = document.createRange();
          rr.setStart(node, i); rr.setEnd(node, i+1);
          const rect = rr.getBoundingClientRect();
          if (lastY === null || Math.abs(rect.y - lastY) > 3) {
            groups.push({y: rect.y, top: rect.top, left: rect.left, right: rect.right,
                         text: text[i]});
            lastY = rect.y;
          } else {
            groups[groups.length-1].right = rect.right;
            groups[groups.length-1].text += text[i];
          }
        }
        res.headlineChars = groups;
      }
      res.factRects = [...document.querySelectorAll('.facts li')].map(e => {
        const r = document.createRange(); r.selectNodeContents(e);
        return {el: e.getBoundingClientRect().toJSON(), text: r.getBoundingClientRect().toJSON()};
      });
      return res;
    }""")
    print(json.dumps(out, indent=1))
    b.close()
