#!/usr/bin/env python3
"""The DOM overlap audit: does any label spill out of its chart or sit on another?

    python scripts/overlap.py [CONTAINER_SELECTOR]     # default 'figure .chart'

Prints `BAD: []` when the page is clean. Two failure modes it catches, both
invisible in a screenshot you are not staring at hard enough:

  * `overflow` — a <text> node whose bounding box crosses its chart's edge
    (a label pushed past the right margin by a long value, a head label that
    starts before the first bar).
  * `overlap`  — two <text> nodes *in the same chart* whose boxes intersect by
    more than 2px in both axes (row labels colliding with a bar's value).

d3 charts are built, not laid out by a browser, so nothing stops them from
drawing text on top of text. This is the only automated check that catches it.
Exit status is 1 when BAD or the console is non-empty.
"""
import asyncio, json, os, sys
from pathlib import Path
from playwright.async_api import async_playwright

JS = """(hostSel) => {
  const bad = [], rects = [];
  for (const el of document.querySelectorAll(hostSel)) {
    const id = el.id, host = el.getBoundingClientRect();
    for (const t of el.querySelectorAll("text")) {
      const r = t.getBoundingClientRect();
      if (r.width === 0) continue;
      if (r.x < host.x - 0.5 || r.x + r.width > host.x + host.width + 0.5)
        bad.push({id, kind: "overflow", t: t.textContent.slice(0, 44),
                  over: +(r.x < host.x ? host.x - r.x
                                       : r.x + r.width - host.x - host.width).toFixed(1)});
      rects.push({id, t: t.textContent.slice(0, 40), r});
    }
  }
  for (let i = 0; i < rects.length; i++) for (let j = i + 1; j < rects.length; j++) {
    const a = rects[i], b2 = rects[j];
    if (a.id !== b2.id) continue;
    const ox = Math.min(a.r.x + a.r.width, b2.r.x + b2.r.width) - Math.max(a.r.x, b2.r.x);
    const oy = Math.min(a.r.y + a.r.height, b2.r.y + b2.r.height) - Math.max(a.r.y, b2.r.y);
    if (ox > 2 && oy > 2)
      bad.push({id: a.id, kind: "overlap", a: a.t, b: b2.t,
                ox: +ox.toFixed(1), oy: +oy.toFixed(1)});
  }
  return bad;
}"""


async def main():
    host = sys.argv[1] if len(sys.argv) > 1 else "figure .chart"
    p_ = Path(os.environ.get("SITE_PORTFILE", "/tmp/siteport.txt")).read_text().strip()
    async with async_playwright() as p:
        b = await p.chromium.launch()
        pg = await b.new_page(viewport={"width": 1440, "height": 1000})
        errs = []
        pg.on("console", lambda m: errs.append(m.type + ": " + m.text)
              if m.type in ("error", "assert") else None)
        pg.on("pageerror", lambda e: errs.append("PAGEERROR " + str(e)))
        await pg.goto(f"http://127.0.0.1:{p_}/index.html", wait_until="networkidle")
        await pg.add_style_tag(content="html{scroll-behavior:auto!important}")
        # scroll to the bottom once so every lazy/transitioned figure has drawn
        await pg.evaluate("window.scrollTo(0, document.body.scrollHeight)")
        await pg.wait_for_timeout(1500)
        bad = await pg.evaluate(JS, host)
        print("BAD:", json.dumps(bad, indent=1))
        print("CONSOLE:", json.dumps(errs))
        await b.close()
    sys.exit(1 if (bad or errs) else 0)


asyncio.run(main())
