#!/usr/bin/env python3
"""Derive a mobile layer from a finished desktop build.

The desktop builds use `1rem = 100px at 1536` so measurements transfer directly
from the mockup. That is exactly wrong for a phone: at 390px it becomes a shrunk
poster with 6px body copy. Mobile needs a real type scale and a real reflow.

Doing that by hand is the same judgement call 36 times, so this does the
mechanical part and leaves the design decisions visible:

  1. type   -- every font-size is read from the rendered page at 1536 and pushed
               through a compressing scale, so a 110px headline becomes ~43px
               while a 25px body becomes 16px. Ordinal relationships survive;
               the range collapses. Without this a phone gets the poster's sizes.
  2. flow   -- absolutely positioned blocks (the poster's coordinate system)
               become static, in DOM order, full width.
  3. stack  -- multi-column grids and nowrap flex rows become one column, and
               `white-space: nowrap` is released so text can wrap instead of
               being clipped.

  python3 tools/responsive.py --src src/index.html --css src/styles.css

Writes `src/mobile.css` and links it from the HTML if it is not already there.
Then look at it: the generated layer gets a build from "broken" to "readable",
and the plate treatment still needs a human.
"""
import argparse
import os
import re
import sys



SCALE_BASE = 25.0   # desktop px that should map to 16px on a phone
SCALE_MIN, SCALE_MAX = 11.0, 46.0


def fragile(px):
    """Compress a desktop font-size into a phone font-size.

    linear scaling is what produces 6px body copy; a pure clamp keeps headlines
    and body too close together. A power curve does both: it preserves the order
    and shrinks the spread. 25px -> 16px, 110px -> 43px, 15px -> 12px.
    """
    v = 16.0 * (px / SCALE_BASE) ** 0.6
    return max(SCALE_MIN, min(SCALE_MAX, v))


def collect(src, width, height):
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = p.chromium.launch()
        pg = b.new_page(viewport={"width": width, "height": height}, device_scale_factor=1)
        pg.goto("file://" + os.path.abspath(src))
        try:
            pg.wait_for_function("document.fonts.status === 'loaded'", timeout=30000)
        except Exception:
            pass
        pg.wait_for_timeout(600)
        data = pg.evaluate("""() => {
          const out = [];
          const seen = new Set();
          document.querySelectorAll('*').forEach(el => {
            if (!el.className || typeof el.className !== 'string') return;
            const cls = el.className.trim().split(/\\s+/).filter(Boolean);
            if (!cls.length) return;
            const key = cls.join('.');
            if (seen.has(key)) return;
            seen.add(key);
            const cs = getComputedStyle(el);
            // a desktop measure handed to a phone is not "no constraint":
            // 7.2rem is 115px at a 16px root. It has to be reset, not omitted.
            const parent = el.parentElement;
            // the parent's *content* width: a block that fills its parent has
            // w === pc, and that is not a measure; padding is not a constraint
            const pcs = parent ? getComputedStyle(parent) : null;
            const pw = parent ? parent.clientWidth
              - parseFloat(pcs.paddingLeft) - parseFloat(pcs.paddingRight) : 0;
            const pfs = parent ? parseFloat(getComputedStyle(parent).fontSize) : 0;
            const r = el.getBoundingClientRect();
            const directText = [...el.childNodes]
              .filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join('');
            const kids = [...el.children];
            const leafText = kids.length > 0 && kids.every(k =>
              k.children.length === 0 && (k.textContent || '').trim().length < 60);
            out.push({
              sel: '.' + cls.join('.'),
              fs: parseFloat(cs.fontSize),
              pos: cs.position,
              ws: cs.whiteSpace,
              display: cs.display,
              cols: cs.gridTemplateColumns,
              dir: cs.flexDirection,
              kids: kids.length,
              maxW: cs.maxWidth,
              w: r.width,
              pw: pw,
              wProps: cs.width,
              directText: !!directText,
              leafText: leafText,
              inherits: Math.abs(parseFloat(cs.fontSize) - pfs) < 0.5,
            });
          });
          return out;
        }""")
        b.close()
    return data


def build_css(data):
    type_rules, flow_rules, stack_rules, measure_rules = [], [], [], []
    for e in data:
        sel = e["sel"]
        fs = e["fs"]
        # text-bearing elements only: a wrapper inheriting 16px is not interesting
        if fs and fs > 1 and not e["inherits"]:
            px = fragile(fs)
            if abs(px - 16) > 0.6:   # 16px is the root default; skip noise
                type_rules.append(f"  {sel} {{ font-size: {px:.1f}px; }}")
        if e["pos"] == "absolute":
            flow_rules.append(
                f"  {sel} {{ position: static; width: auto; height: auto;"
                f" left: auto; top: auto; right: auto; bottom: auto; }}\n")
        if e["ws"] == "nowrap":
            stack_rules.append(f"  {sel} {{ white-space: normal; }}\n")
        # a measure is anything that constrains width: max-width, or a fixed
        # width narrower than the parent. Both are expressed in poster rem and
        # both must be released, or the phone inherits a 115px column.
        release = []
        if e["maxW"] not in ("none", ""):
            release.append("max-width: none")
        if (e["pw"] and abs(e["w"] - e["pw"]) > 4
                and (e["directText"] or e["leafText"])):
            release.append("width: auto")
        if release:
            measure_rules.append(f"  {sel} {{ {'; '.join(sorted(set(release)))}; }}\n")

        if e["display"] in ("flex", "grid") and e["kids"] > 1:
            # short text children are a run of phrases, not layout regions:
            # they should wrap to the viewport, not each take a line
            if e["leafText"]:
                stack_rules.append(
                    f"  {sel} {{ display: flex; flex-wrap: wrap; align-items: baseline; "
                    f"gap: 2px 10px; }}\n")
            else:
                stack_rules.append(
                    f"  {sel} {{ display: block; }}\n  {sel} > * {{ width: auto; }}\n")
    return type_rules, flow_rules, stack_rules, measure_rules


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default="src/index.html")
    ap.add_argument("--css", default="src/styles.css")
    ap.add_argument("--out", default="src/mobile.css")
    ap.add_argument("--breakpoint", type=int, default=900)
    ap.add_argument("--base-width", type=int, default=1536)
    ap.add_argument("--base-height", type=int, default=864)
    a = ap.parse_args()

    data = collect(a.src, a.base_width, a.base_height)
    type_rules, flow_rules, stack_rules, measure_rules = build_css(data)

    css = [f"""/* Generated by tools/responsive.py -- then edited by hand.
   Breakpoint {a.breakpoint}px. Desktop is a 1536-wide poster with
   1rem = 100px; none of that survives on a phone, so this block replaces the
   coordinate system rather than scaling it. */
@media (max-width: {a.breakpoint}px) {{
  html {{ font-size: 16px; }}
  body {{ min-height: auto; overflow-x: hidden; }}
"""]
    css.append("  /* type: desktop px -> phone px, ordinal order kept */\n")
    css += [r + "\n" for r in type_rules]
    css.append("\n  /* flow: the poster's absolute boxes become stacked blocks */\n")
    css += flow_rules
    css.append("\n  /* measures: desktop column widths are poster rem, release them */\n")
    css += measure_rules
    css.append("\n  /* stack: multi-column rows become one column */\n")
    css += sorted(set(stack_rules))
    css.append("}\n")
    out = "".join(css)
    open(a.out, "w").write(out)

    html = open(a.src).read()
    if "mobile.css" not in html:
        html = html.replace('<link rel="stylesheet" href="styles.css">',
                            '<link rel="stylesheet" href="styles.css">\n'
                            '<link rel="stylesheet" href="mobile.css" media="(max-width: %dpx)">' % a.breakpoint)
        open(a.src, "w").write(html)
    print(f"wrote {a.out}: {len(type_rules)} type, {len(flow_rules)} flow, "
          f"{len(measure_rules)} measure, {len(set(stack_rules))} stack rules")


if __name__ == "__main__":
    main()
