"""
End-to-end tests for WebSocket display using Playwright.
"""

import time

import pytest


class TestWebSocketE2E:
    """End-to-end tests for WebSocket display with browser."""

    @pytest.mark.e2e
    def test_websocket_server_starts(self):
        """Test that WebSocket server starts and serves HTTP."""
        import threading

        from engine.display.backends.websocket import WebSocketDisplay

        display = WebSocketDisplay(host="127.0.0.1", port=18765)

        server_thread = threading.Thread(target=display.start_http_server)
        server_thread.daemon = True
        server_thread.start()

        time.sleep(1)

        try:
            import urllib.request

            response = urllib.request.urlopen("http://127.0.0.1:18765", timeout=5)
            assert response.status == 200
            content = response.read().decode("utf-8")
            assert len(content) > 0
        finally:
            display.cleanup()
            time.sleep(0.5)

    @pytest.mark.e2e
    @pytest.mark.skipif(
        not pytest.importorskip("playwright", reason="playwright not installed"),
        reason="playwright not installed",
    )
    def test_websocket_browser_connection(self):
        """Test WebSocket connection with actual browser."""
        import threading

        from playwright.sync_api import sync_playwright

        from engine.display.backends.websocket import WebSocketDisplay

        display = WebSocketDisplay(host="127.0.0.1", port=18767)

        server_thread = threading.Thread(target=display.start_server)
        server_thread.daemon = True
        server_thread.start()

        http_thread = threading.Thread(target=display.start_http_server)
        http_thread.daemon = True
        http_thread.start()

        time.sleep(1)

        try:
            with sync_playwright() as p:
                browser = p.chromium.launch(headless=True)
                page = browser.new_page()

                page.goto("http://127.0.0.1:18767")
                time.sleep(0.5)

                title = page.title()
                assert len(title) >= 0

                browser.close()
        finally:
            display.cleanup()
            time.sleep(0.5)
