"""Regression tests for the tablet-band responsive fixes.

The Playwright sweep (``tests/responsive_check.py``) found 17 overflowing
page/width combinations in the 768–1024px band: the shared header's 17-link
nav has a min-content width of ~1000px and several templates pin
``nav{display:flex}`` without ``flex-wrap``, and wide data tables (memory /
claims) cannot shrink below the min-content width of their cells.

These tests assert the structural CSS invariants that fixed that band, so a
future edit cannot silently reopen the overflow. They run without a browser.
"""

from __future__ import annotations

import os
import re

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CSS_PATH = os.path.join(APP_DIR, "static", "css", "jarvis.css")
CHECK_PATH = os.path.join(APP_DIR, "tests", "responsive_check.py")
TEMPLATES = os.path.join(APP_DIR, "templates")


def _css() -> str:
    with open(CSS_PATH, encoding="utf-8") as fh:
        return fh.read()


def _block(selector: str, css: str) -> str:
    """Return the declaration body of the first rule matching ``selector``."""
    m = re.search(re.escape(selector) + r"\s*\{([^}]*)\}", css, re.S)
    assert m, f"rule for {selector!r} not found in jarvis.css"
    return m.group(1)


def test_tablet_band_breakpoint_exists():
    """A mid-range breakpoint must cover the 768–1024px gap."""
    css = _css()
    bands = re.findall(
        r"@media\s*\(min-width:\s*(\d+)px\)\s*and\s*\(max-width:\s*(\d+)px\)", css
    )
    assert bands, "no bounded media query found — the tablet band is missing"
    assert any(int(lo) <= 768 and int(hi) >= 1024 for lo, hi in bands), (
        "tablet band must span 768px..1024px, found: %s" % bands
    )


def test_nav_wraps_in_tablet_band():
    """The header nav is allowed to wrap onto its own row between 641–1180px."""
    css = _css()
    # the tablet block is the one bounded query; grab everything after it
    start = re.search(r"@media\s*\(min-width:\s*641px\)", css)
    assert start, "tablet media query missing"
    tablet = css[start.start():]
    header_nav = _block("header nav", tablet)
    assert "flex-wrap: wrap" in header_nav
    assert "min-width: 0" in header_nav
    assert "order:" in header_nav  # drops below the title/stat row


def test_tables_scroll_in_tablet_band():
    """Wide tables get their own horizontal scroll box instead of the page."""
    css = _css()
    start = re.search(r"@media\s*\(min-width:\s*641px\)", css)
    tablet = css[start.start():]
    table = _block("table", tablet)
    assert "display: block" in table
    assert "overflow-x: auto" in table
    assert "max-width: 100%" in table


def test_phone_card_layout_not_regressed():
    """Phone (<=640px) still turns tables into labelled cards."""
    css = _css()
    phone_start = css.index("@media (max-width: 640px)")
    phone = css[phone_start:]
    assert "table thead { display: none; }" in phone
    assert "table td::before" in phone
    # the phone block must stay after the tablet band so it wins the cascade
    assert phone_start > css.index("@media (min-width: 641px)")


def test_every_audited_page_loads_shared_css():
    """All pages the sweep visits must link jarvis.css, else fixes don't apply."""
    audited = [
        "dashboard", "opportunities", "verification", "live_data", "outreach",
        "memory", "audit", "measurement", "senses", "bots", "phone", "avatar",
        "schedules", "voice",
    ]
    missing = []
    for name in audited:
        path = os.path.join(TEMPLATES, name + ".html")
        assert os.path.exists(path), f"missing template {path}"
        with open(path, encoding="utf-8") as fh:
            if "jarvis.css" not in fh.read():
                missing.append(name)
    assert not missing, f"templates not loading shared responsive CSS: {missing}"


def test_audit_script_resolves_local_browser():
    """The sweep must pin a pre-baked browser instead of downloading one."""
    with open(CHECK_PATH, encoding="utf-8") as fh:
        src = fh.read()
    assert "executable_path" in src
    assert "/ms-playwright/chromium" in src  # glob for the baked build
    assert "playwright install" not in src


def test_audit_script_covers_full_width_range():
    """15 pages x 9 widths, 1680px down to 420px."""
    with open(CHECK_PATH, encoding="utf-8") as fh:
        src = fh.read()
    widths = re.search(r"WIDTHS = \[([^\]]*)\]", src).group(1)
    parsed = [int(w) for w in re.findall(r"\d+", widths)]
    assert parsed[0] == 1680 and parsed[-1] == 420
    assert len(parsed) == 9
    assert parsed == sorted(parsed, reverse=True)

    pages = re.search(r"PAGES = \[([^\]]*)\]", src, re.S).group(1)
    assert len(re.findall(r'"[^"]+"', pages)) == 15


# ---------------------------------------------------------------------------
# Regressions found by tests/responsive_probe.py (the strict probe).
#
# The original sweep only compared documentElement.scrollWidth, which is masked
# by `html,body{overflow-x:hidden}` on live_data/outreach/schedules, and it only
# visited 15 pages. The strict probe measured real element right edges on the
# pages the sweep skipped and found two genuine overflows at 420-600px:
#   * /ui/jobs/<id>  - job.html header had `display:flex` with no flex-wrap, so
#                      its 10 nav links forced the page ~318px wide.
#   * /bots/<id>     - a 64-char sha256 inside <code> has no break opportunity.
# ---------------------------------------------------------------------------


def _template(name: str) -> str:
    with open(os.path.join(TEMPLATES, name), encoding="utf-8") as fh:
        return fh.read()


def test_job_header_wraps():
    """job.html header must wrap; it is the only template that did not."""
    src = _template("job.html")
    header = re.search(r"header\{([^}]*)\}", src).group(1)
    assert "display:flex" in header.replace(" ", "")
    assert "flex-wrap:wrap" in header.replace(" ", ""), (
        "job.html header must set flex-wrap:wrap or its 10 nav links overflow"
    )


def test_job_has_narrow_screen_rules():
    src = _template("job.html")
    assert "@media (max-width: 640px)" in src
    assert "white-space: normal" in src  # .kv td:first-child was nowrap


def test_bot_detail_wraps_long_hashes():
    """The sha256 <code> must be breakable or it overflows at 420px."""
    src = _template("bot_detail.html")
    assert "overflow-wrap:anywhere" in src
    assert "@media (max-width: 640px)" in src
    assert "word-break: break-all" in src


def test_every_template_header_wraps():
    """No template may ship a non-wrapping flex header."""
    offenders = []
    for name in sorted(os.listdir(TEMPLATES)):
        if not name.endswith(".html"):
            continue
        src = _template(name)
        for m in re.finditer(r"header\{([^}]*)\}", src):
            body = m.group(1).replace(" ", "")
            if "display:flex" in body and "flex-wrap" not in body:
                offenders.append(name)
                break
    assert not offenders, f"non-wrapping flex header in: {offenders}"


def test_strict_probe_exists_and_skips_scroll_containers():
    """The probe must not flag content inside legitimate scroll containers."""
    path = os.path.join(APP_DIR, "tests", "responsive_probe.py")
    assert os.path.exists(path)
    with open(path, encoding="utf-8") as fh:
        src = fh.read()
    assert "overflowX" in src and "scrollable" in src
    assert "offCanvas" in src  # the drawer is parked off-screen by design
    assert "EXTRA_PAGES" in src  # covers pages the original sweep skipped
    assert "executable_path" in src
