"""fed-web's UI gate (WUI-07) — thin, thanks to the mgf-uitest-web fixture surface.

These specs drive this console in a real pinned Chromium and assert what an
in-process ``TestClient`` structurally cannot see: that CSS and JS actually load,
that the rendered layout holds at each viewport, and that the page is accessible.
Every GET page renders with clean desktop layout, a real POST interaction works,
the UNKNOWN path stays an honest 200, and the layout check is shown to catch an
injected regression on the live page (the check itself is under test, not trusted).

The three findings this harness originally surfaced on fed-web are now **real
gates, not xfails** — each was fixed and published, so each must stay fixed:

    #1 health  — was a FALSE finding: a ``/global-tokens.css`` 404 that turned out
                 to be a system-Chrome fallback artifact. Under the pinned browser
                 fed-web loads clean. (Why the harness pins the browser: a different
                 build resolves ``@import`` differently and invents findings that
                 don't reproduce.)
    #2 a11y    — colour-contrast (WCAG AA) on ``.fw-act--gold`` against the dark
                 topbar. Fixed in fed-web 0.2.1 (the bright brand gold).
    #3 mobile  — the brand-kit topbar overflowed at 390px, forcing sideways scroll.
                 Fixed in mgf-brand-web 0.5.2 (topbar wrap + rail stack).

If one of these ever fails again, the regression is real and it shipped to a user's
browser — that is the whole point of this tier.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
    from mgf.uitest_web import Console

#: Every GET page fed-web serves for the synthetic alpha/beta federation.
PAGES = [
    "/",
    "/p/alpha",
    "/p/beta",
    "/p/alpha/roadmap",
    "/p/beta/architecture",
    "/p/alpha/feedback",
    "/p/alpha/review-pack",
    "/p/alpha/live",
]


def _snap_name(path: str) -> str:
    return path.strip("/").replace("/", "-") or "overview"


# --------------------------------------------------------------------------- #
# pillars fed-web already passes: functional + desktop layout                 #
# --------------------------------------------------------------------------- #
@pytest.mark.e2e
@pytest.mark.parametrize("path", PAGES)
def test_page_renders_with_clean_desktop_layout(console: Console, path: str) -> None:
    console.open(path)
    console.assert_status(200)
    console.assert_layout_clean()
    console.snapshot(_snap_name(path))


@pytest.mark.e2e
def test_overview_lists_the_participants(console: Console) -> None:
    console.open("/")
    body = console.text()
    assert "alpha" in body and "beta" in body, "overview did not list the participants"


@pytest.mark.e2e
def test_unknown_project_is_an_honest_200(console: Console) -> None:
    """A project not in the federation renders UNKNOWN at HTTP 200 — never a 500."""
    console.open("/p/does-not-exist")
    console.assert_status(200)
    assert "does-not-exist" in console.text() or "UNKNOWN" in console.text().upper()
    console.assert_layout_clean()


@pytest.mark.e2e
def test_check_all_action_rerenders(console: Console) -> None:
    """Driving a real POST interaction: 'Check all' re-renders the matrix."""
    console.open("/")
    console.page.get_by_role("button", name="Check all").click()
    console.page.wait_for_load_state("load")
    body = console.text()
    assert "alpha" in body and "beta" in body, "matrix did not re-render after Check all"
    console.assert_layout_clean()


# --------------------------------------------------------------------------- #
# the headline proof: the layout check catches a regression on the LIVE page  #
# --------------------------------------------------------------------------- #
@pytest.mark.e2e
def test_layout_check_catches_an_injected_regression(console: Console) -> None:
    console.open("/")
    assert console.audit_layout().ok, "precondition: the overview should start layout-clean"
    # Inject a regression: a wide element that escapes every container.
    console.page.evaluate(
        "() => { const d = document.createElement('div');"
        " d.style.width = '4000px'; d.style.height = '10px';"
        " d.textContent = 'injected-regression';"
        " document.body.appendChild(d); }"
    )
    report = console.audit_layout()
    assert not report.ok, "the layout check should catch the injected 4000px overflow"
    assert report.horizontal_scroll, "the injected element should force horizontal page scroll"


# --------------------------------------------------------------------------- #
# known findings — xfail gates (flip to real gates when fed-web is fixed)      #
# --------------------------------------------------------------------------- #
@pytest.mark.e2e
def test_overview_is_healthy(console: Console) -> None:
    """No console errors, no failed requests, no HTTP errors on load.

    (This was briefly a false 'finding #1' — a /global-tokens.css 404 — that turned
    out to be a system-Chrome fallback artifact. Under the pinned browser fed-web
    loads clean, so this is a real, passing gate.)
    """
    console.open("/")
    console.assert_healthy()


@pytest.mark.e2e
def test_overview_is_accessible(console: Console) -> None:
    """No serious/critical axe violations (finding #2 fixed: fw-act--gold on dark chrome)."""
    console.open("/")
    console.assert_accessible()


@pytest.mark.e2e
@pytest.mark.parametrize("viewport", ["mobile"], indirect=True)
def test_overview_mobile_layout_is_clean(console: Console) -> None:
    """No sideways scroll at 390px (finding #3 fixed: the brand-kit topbar now wraps)."""
    console.open("/")
    console.assert_layout_clean()
