"""Strict responsive overflow probe (v2) — measures *unreachable* content.

Why this exists
---------------
``responsive_check.py`` compares ``documentElement.scrollWidth`` to
``clientWidth``. Three templates (live_data, outreach, schedules) set
``html,body{overflow-x:hidden}``, which makes that comparison report 0 even
when content is clipped off-screen. A naive "max element right edge" check is
wrong in the other direction: it flags content that lives inside a legitimate
horizontal scroll container (the phone nav strip, ``table{overflow-x:auto}``)
and the off-canvas drawer.

This probe reports only content the user genuinely cannot reach:

* an element whose right edge exceeds the viewport, AND
* no ancestor (or itself) offers horizontal scrolling (overflow-x auto/scroll), AND
* it is not inside an off-canvas fixed panel (the drawer, translated 100%).

Run: ``python3 tests/responsive_probe.py``
Exit code 1 if real overflow is found.
"""
import glob
import json
import os
import re
import sys

from playwright.sync_api import sync_playwright

BASE = os.environ.get("JARVIS_BASE", "http://localhost:3000")

# The 15 canonical pages the original sweep covers ...
PAGES = [
    "/", "/pipeline", "/opportunities", "/ui/verification", "/live-data",
    "/outreach", "/memory", "/audit", "/measurement", "/senses", "/bots",
    "/phone", "/avatar", "/schedules", "/voice",
]
# ... plus pages that render but the original sweep never visited. These are
# where the probe actually found overflow (job detail header, bot detail hash).
EXTRA_PAGES = [
    "/ui/opportunities", "/verification", "/components", "/states",
]
WIDTHS = [1680, 1440, 1280, 1024, 900, 768, 600, 500, 420]

JS = r"""
() => {
  const de = document.documentElement;
  const vw = de.clientWidth;
  const scrollable = (el) => {
    for (let n = el; n && n !== document.documentElement; n = n.parentElement) {
      const ox = getComputedStyle(n).overflowX;
      if (ox === 'auto' || ox === 'scroll') return true;
    }
    return false;
  };
  const offCanvas = (el) => {
    for (let n = el; n && n !== document.documentElement; n = n.parentElement) {
      const cs = getComputedStyle(n);
      if (cs.position === 'fixed') {
        const r = n.getBoundingClientRect();
        // fixed panel parked outside the viewport (drawer / hidden sheet)
        if (r.left >= vw - 1 || r.right <= 1) return true;
      }
    }
    return false;
  };
  let worst = null, count = 0;
  for (const el of document.querySelectorAll('body *')) {
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') continue;
    const r = el.getBoundingClientRect();
    if (r.width === 0 && r.height === 0) continue;
    const right = r.right + window.scrollX;
    if (right <= vw + 1) continue;
    if (scrollable(el) || offCanvas(el)) continue;
    count++;
    const over = Math.round(right - vw);
    if (!worst || over > worst.over) {
      worst = {over, tag: el.tagName.toLowerCase(),
               cls: (el.className && String(el.className).slice(0, 70)) || '',
               id: el.id || '', w: Math.round(r.width),
               text: (el.innerText || '').trim().slice(0, 50)};
    }
  }
  // body-level clipping: content wider than the body box while overflow is hidden
  const bcs = getComputedStyle(document.body);
  const bodyClipped = (bcs.overflowX === 'hidden' && document.body.scrollWidth > document.body.clientWidth + 1)
      ? document.body.scrollWidth - document.body.clientWidth : 0;
  return {vw, overflow: worst ? worst.over : 0, worst, count, bodyClipped,
          docOverflow: de.scrollWidth - vw};
}
"""


def find_chromium():
    env = os.environ.get("JARVIS_CHROME_PATH")
    if env and os.path.exists(env):
        return env
    for pattern in (
        "/ms-playwright/chromium-*/chrome-linux64/chrome",
        "/ms-playwright/chromium-*/chrome-linux/chrome",
        "/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-linux64/chrome-headless-shell",
        os.path.expanduser("~/.cache/ms-playwright/chromium-*/chrome-linux*/chrome"),
    ):
        hits = sorted(glob.glob(pattern))
        if hits:
            return hits[-1]
    for name in ("/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"):
        if os.path.exists(name):
            return name
    return None


def _extra_pages():
    """Extra pages, with a real job id resolved from the running app."""
    import urllib.request
    pages = list(EXTRA_PAGES)
    try:
        with urllib.request.urlopen(BASE + "/jobs", timeout=10) as fh:
            body = fh.read().decode("utf-8", "replace")
        m = re.search(r"[0-9a-f]{32}", body)
        if m:
            pages += ["/ui/jobs/" + m.group(0), "/jobs/" + m.group(0)]
    except Exception as exc:  # app down / no jobs yet
        print(f"(skipping job-detail pages: {exc})")
    try:
        with urllib.request.urlopen(BASE + "/api/bots", timeout=10) as fh:
            body = fh.read().decode("utf-8", "replace")
        m = re.search(r'"id"\s*:\s*(\d+)', body)
        if m:
            pages.append("/bots/" + m.group(1))
    except Exception as exc:
        print(f"(skipping bot-detail page: {exc})")
    return pages


def main():
    exe = find_chromium()
    print(f"browser executable: {exe or '(playwright default)'}")
    pages = PAGES + _extra_pages()
    print(f"pages: {len(pages)}")
    results = []
    with sync_playwright() as p:
        browser = p.chromium.launch(
            args=["--no-sandbox", "--disable-dev-shm-usage"],
            **({"executable_path": exe} if exe else {}),
        )
        for width in WIDTHS:
            page = browser.new_page(viewport={"width": width, "height": 900})
            for path in pages:
                page.goto(BASE + path, wait_until="domcontentloaded", timeout=30000)
                page.wait_for_timeout(120)
                r = page.evaluate(JS)
                results.append({"width": width, "path": path, **r})
            page.close()
        browser.close()

    bad = [r for r in results if r["overflow"] > 1]
    bodyclip = [r for r in results if r["bodyClipped"] > 1]
    print(f"checked {len(results)} page/width combinations")
    print(f"UNREACHABLE OVERFLOW: {len(bad)}")
    for r in sorted(bad, key=lambda x: -x["overflow"]):
        print(f"  {r['width']}px {r['path']}: {r['overflow']}px x{r['count']} worst={r['worst']}")
    print(f"BODY-CLIPPED (overflow-x:hidden hiding content): {len(bodyclip)}")
    for r in sorted(bodyclip, key=lambda x: -x["bodyClipped"]):
        print(f"  {r['width']}px {r['path']}: body clipped {r['bodyClipped']}px")
    with open("/tmp/responsive_probe.json", "w") as fh:
        json.dump(results, fh, indent=1)
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())
