"""Contract tests: prove each pillar-check catches its target — with teeth.

These are console-free and deterministic: they build a tiny known-broken (or
known-clean) DOM with ``set_content`` and assert the check reacts correctly. They
pin the checks' behaviour independent of any console, so a future refactor can't
silently blunt them. Includes a guard for the precision fix (content inside an
``overflow-x:auto`` scroller must NOT be flagged).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from mgf.uitest_web import audit_layout, scan_a11y, watch_health

if TYPE_CHECKING:
    from playwright.sync_api import Page

# These pin the checks' contract but drive a real Chromium (set_content), so they
# are integration (tier-2), not tier-1 unit: they need the browser the test job
# installs via `[tool.mgf-fed] browser = true`. Tier-2 keeps them inside the
# per-PR --tier 0-2 gate, which is where the checks' teeth belong.
pytestmark = pytest.mark.integration


@pytest.mark.contract
def test_layout_flags_element_past_the_viewport(ui_page: Page) -> None:
    ui_page.set_content(
        "<body style='margin:0'><div style='width:4000px;height:20px'>x</div></body>"
    )
    report = audit_layout(ui_page)
    assert not report.ok
    assert report.horizontal_scroll
    assert any(v["kind"] == "viewport-overflow-x" for v in report.violations), report.describe()


@pytest.mark.contract
def test_layout_flags_text_spilling_past_its_box(ui_page: Page) -> None:
    ui_page.set_content(
        "<body style='margin:0'><div style='width:40px;overflow:visible;white-space:nowrap'>"
        "UnbreakableLongTokenThatExceedsFortyPixels</div></body>"
    )
    report = audit_layout(ui_page)
    assert any(v["kind"] == "text-overflow" for v in report.violations), report.describe()


@pytest.mark.contract
def test_layout_ignores_content_inside_a_scroller(ui_page: Page) -> None:
    """The precision fix: a wide child inside overflow-x:auto is a valid pattern."""
    ui_page.set_content(
        "<body style='margin:0'><div style='width:200px;overflow-x:auto'>"
        "<div style='width:3000px;height:20px'>x</div></div></body>"
    )
    report = audit_layout(ui_page)
    assert not report.horizontal_scroll, report.describe()
    assert not any(v["kind"] == "viewport-overflow-x" for v in report.violations), report.describe()


@pytest.mark.contract
def test_layout_passes_a_clean_page(ui_page: Page) -> None:
    ui_page.set_content(
        "<body style='margin:0'><main><h1>Clean</h1><p>Nothing spills here.</p></main></body>"
    )
    assert audit_layout(ui_page).ok


@pytest.mark.contract
def test_a11y_flags_a_missing_image_alt(ui_page: Page) -> None:
    ui_page.set_content(
        "<html lang='en'><head><title>t</title></head>"
        "<body><main><img src='x.png'></main></body></html>"
    )
    violations = scan_a11y(ui_page)
    assert any(v.get("id") == "image-alt" for v in violations), [v.get("id") for v in violations]


@pytest.mark.contract
def test_health_catches_a_404_subresource(ui_page: Page) -> None:
    ui_page.route(
        "**/missing.png",
        lambda route: route.fulfill(status=404, content_type="image/png", body=b""),
    )
    watch = watch_health(ui_page)
    ui_page.set_content("<body><img src='https://example.com/missing.png' alt='x'></body>")
    ui_page.wait_for_timeout(300)
    assert any(r["status"] == 404 for r in watch.error_responses), watch.describe()
