"""Responsive overflow audit: 1680px down to 420px, every page.

Reports document.scrollWidth vs clientWidth and names the widest offending
element when a page overflows horizontally.
"""
import glob
import json
import os
import sys

from playwright.sync_api import sync_playwright

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


def _find_local_chromium():
    """Resolve a pre-baked browser so the audit never has to download one.

    The sandbox ships Chromium builds that can be older/newer than the
    installed Playwright driver revision; pin an explicit executable_path
    instead of relying on the revision the driver expects.
    """
    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",
        "/root/.cache/ms-playwright/chromium-*/chrome-linux*/chrome",
        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
PAGES = [
    "/", "/pipeline", "/opportunities", "/ui/verification", "/live-data",
    "/outreach", "/memory", "/audit", "/measurement", "/senses", "/bots",
    "/phone", "/avatar", "/schedules", "/voice",
]
WIDTHS = [1680, 1440, 1280, 1024, 900, 768, 600, 500, 420]

JS = """
() => {
  const de = document.documentElement;
  const vw = de.clientWidth;
  const overflow = de.scrollWidth - vw;
  let worst = null;
  if (overflow > 1) {
    for (const el of document.querySelectorAll('body *')) {
      const r = el.getBoundingClientRect();
      if (r.width === 0 && r.height === 0) continue;
      const right = r.right + window.scrollX;
      if (right > vw + 1) {
        const over = right - vw;
        if (!worst || over > worst.over) {
          worst = {
            over: Math.round(over),
            tag: el.tagName.toLowerCase(),
            cls: (el.className && String(el.className).slice(0, 60)) || '',
            id: el.id || '',
            w: Math.round(r.width),
          };
        }
      }
    }
  }
  return {vw, scrollWidth: de.scrollWidth, overflow, worst};
}
"""

results = []
EXECUTABLE = _find_local_chromium()
print(f"browser executable: {EXECUTABLE or '(playwright default)'}")

with sync_playwright() as p:
    browser = p.chromium.launch(
        args=["--no-sandbox", "--disable-dev-shm-usage"],
        **({"executable_path": EXECUTABLE} if EXECUTABLE 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]
print(f"checked {len(results)} page/width combinations")
print(f"OVERFLOWING: {len(bad)}")
for r in bad:
    print(f"  {r['width']}px {r['path']}: overflow={r['overflow']}px worst={r['worst']}")
with open("/tmp/responsive.json", "w") as fh:
    json.dump(results, fh, indent=1)
sys.exit(0)
