#!/usr/bin/env python3
"""Remove hard-coded line breaks from a headline and let the measure do the work.

A headline built from one `<span class="ln">` per line reproduces the mockup
exactly and then stops being a headline: edit the text and the layout lies. The
mockup's breaks are an accident of its column width, so the honest encoding is
plain text plus a `max-width` that happens to break in the same places at the
reference width. Below the breakpoint the same text then reflows naturally.

The width is a *window*, not a point. If the longest intended line measures L and
the first word of the next line is W, any measure in [L, L + W) produces the same
breaks. This tool finds that window by measuring the real break points in the
browser (character by character, so it is exact rather than estimated) and picks
its midpoint, which leaves the most room for font-loading differences.

  python3 tools/unwrap.py --src src/index.html --css src/styles.css
  python3 tools/unwrap.py --src src/index.html --css src/styles.css --dry-run
"""
import argparse
import os
import re

LN = re.compile(r'<span class="ln">(.*?)</span>', re.S)


def extract(html):
    """Return (new_html, [line_html, ...]) for the first element holding .ln spans."""
    pat = re.compile(r'<(h1|div|p)\b[^>]*>(.*?)</\1>', re.S)
    for m in pat.finditer(html):
        lines = LN.findall(m.group(2))
        if lines:
            plain = " ".join(" ".join(l.split()) for l in lines)
            tag = m.group(1)
            start = m.start()
            open_tag = re.match(r'<[^>]*>', m.group(0)).group(0)
            new = f"{open_tag}{plain}</{tag}>"
            return html[:start] + new + html[m.end():], lines
    return html, []


def line_boxes(pg, selector):
    """The text of each rendered line, obtained by walking characters in a Range.

    Reading per character is slower than guessing from rects, but it is exact:
    it reports where the browser actually broke, including inside a word.
    """
    return pg.evaluate("""(sel) => {
      const el = document.querySelector(sel);
      if (!el) return null;
      const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
      const nodes = []; let n;
      while ((n = walker.nextNode())) nodes.push(n);
      if (!nodes.length) return null;
      const lines = [];
      let current = '', lastTop = null;
      const r = document.createRange();
      for (const node of nodes) {
        const t = node.textContent;
        for (let i = 0; i < t.length; i++) {
          r.setStart(node, i); r.setEnd(node, i + 1);
          const b = r.getBoundingClientRect();
          if (!b.width && !b.height) { current += t[i]; continue; }
          const top = Math.round(b.top);
          if (lastTop === null) lastTop = top;
          if (top > lastTop + 2) { lines.push(current); current = ''; lastTop = top; }
          current += t[i];
        }
      }
      if (current.trim()) lines.push(current);
      return lines.map(s => s.replace(/\\s+/g, ' ').trim()).filter(Boolean);
    }""", selector)


def measure_width(pg, selector, width_px):
    # `width`, not `max-width`: a max-width can never exceed the containing
    # block, so a line that needs to be wider than its column would look
    # unreachable no matter how wide we swept
    pg.evaluate("""([sel, w]) => {
      const el = document.querySelector(sel);
      el.style.maxWidth = 'none';
      el.style.width = w === null ? '' : w + 'px';
    }""", [selector, width_px])
    pg.wait_for_timeout(30)
    return line_boxes(pg, selector)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default="src/index.html")
    ap.add_argument("--css", default="src/styles.css")
    ap.add_argument("--selector", default=".headline")
    ap.add_argument("--width", type=int, default=1536)
    ap.add_argument("--height", type=int, default=864)
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--expect", default=None,
                    help="line1|line2 when the .ln spans are already gone")
    a = ap.parse_args()

    html = open(a.src).read()
    new_html, lines = extract(html)
    if not lines:
        if not a.expect:
            raise SystemExit("no .ln spans found (pass --expect \"line1|line2\")")
        intended = [" ".join(l.split()) for l in a.expect.split("|")]
        new_html = html
    else:
        intended = [" ".join(l.split()) for l in lines]
    print("intended lines:")
    for l in intended:
        print("   ", l)

    if not a.dry_run:
        open(a.src, "w").write(new_html)

    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = p.chromium.launch()
        pg = b.new_page(viewport={"width": a.width, "height": a.height}, device_scale_factor=1)
        pg.goto("file://" + os.path.abspath(a.src))
        try:
            pg.wait_for_function("document.fonts.status === 'loaded'", timeout=30000)
        except Exception:
            pass
        pg.wait_for_timeout(500)

        # with no constraint, how wide is the widest single line?
        # clear a hard nowrap while measuring: it would make every width look
        # identical, and it is exactly what has to go from the CSS afterwards
        had_nowrap = pg.evaluate(
            "(s)=>{const e=document.querySelector(s),w=getComputedStyle(e).whiteSpace;"
            "e.style.whiteSpace='normal';return w==='nowrap';}", a.selector)
        if had_nowrap:
            print("  element was white-space: nowrap -- remove it from the CSS")
        pg.evaluate("(s)=>{document.querySelector(s).style.maxWidth='none'}", a.selector)
        pg.wait_for_timeout(50)
        natural = line_boxes(pg, a.selector)
        print(f"\nunconstrained: {len(natural)} line(s)")

        # sweep the measure and record which widths reproduce the intended breaks
        el_w = pg.evaluate("(s)=>document.querySelector(s).getBoundingClientRect().width", a.selector)
        # sweep past the container: a block may be wider than its parent, and a
        # line that just fails to fit (this build's second line needs 1452px in
        # a 1456px column) otherwise looks like an impossible set of breaks
        lo, hi = 60, int(el_w) + 400
        good = []
        for w in range(lo, hi + 1, 2):
            got = measure_width(pg, a.selector, w)
            if got == intended:
                good.append(w)
        # keep only the contiguous run containing the widest result
        runs, cur = [], []
        for w in good:
            if cur and w - cur[-1] > 4:
                runs.append(cur); cur = []
            cur.append(w)
        if cur:
            runs.append(cur)
        runs = [r for r in runs if len(r) > 2] or runs
        b.close()

    if not runs:
        print("\nno width reproduces those breaks — the text or the type has drifted;"
              " check the line contents against the mockup")
        raise SystemExit(1)

    widest = max(runs, key=len)
    pick = widest[len(widest) // 2]
    print(f"\nvalid windows (px): " + ", ".join(f"{r[0]}-{r[-1]}" for r in runs))
    print(f"pick {pick}px = {pick / 100:.3f}rem  (window {widest[0]}–{widest[-1]}, "
          f"tolerance ±{(widest[-1] - widest[0]) / 2 / 100:.2f}rem)")

    parent_w = pg_width = None
    css = open(a.css).read()
    rule = css.split(a.selector + " {")[1].split("}")[0]
    if pick > el_w + 2:
        decl = "width: %.3frem; max-width: none;" % (pick / 100)
        print(f"note: {pick}px is wider than the {int(el_w)}px container, so this is a width, not a max-width")
    else:
        decl = "max-width: %.3frem;" % (pick / 100)
    if "max-width" not in rule and "width:" not in rule:
        css = css.replace(a.selector + " {", a.selector + " {\n            " + decl, 1)
        if not a.dry_run:
            open(a.css, "w").write(css)
            print(f"wrote {a.selector} {{ {decl} }} into {a.css}")
    else:
        print(f"{a.selector} already sets a width; set it to {pick / 100:.3f}rem by hand")

    # the mobile layer must not inherit a measure expressed in desktop rem
    mobile = os.path.join(os.path.dirname(a.css), "mobile.css")
    if os.path.exists(mobile):
        m = open(mobile).read()
        if a.selector not in m:
            print(f"note: add  {a.selector} {{ max-width: none; }}  to {mobile}")


if __name__ == "__main__":
    main()
