"""The virtual display must start even when /tmp cannot be trusted.

Agents run with a private /tmp overlay, so the socket paths under /tmp/.X11-unix
say nothing about which displays are taken; the abstract socket Xvfb binds is
shared across every namespace. Picking a number from the visible sockets is how
`Xvfb :90 never started` happened.
"""

from __future__ import annotations

import shutil
import subprocess

import pytest

import browser

pytestmark = pytest.mark.skipif(shutil.which("Xvfb") is None, reason="Xvfb not installed")


def _stop(proc: subprocess.Popen) -> None:
    proc.terminate()
    try:
        proc.wait(10)
    except subprocess.TimeoutExpired:
        proc.kill()
        proc.wait(5)


def test_a_second_display_starts_alongside_the_first():
    """Two live servers at once: the second must not be handed the first's number."""
    first, first_display = browser.start_xvfb()
    try:
        second, second_display = browser.start_xvfb()
        try:
            assert first_display != second_display
            assert first.poll() is None and second.poll() is None
        finally:
            _stop(second)
    finally:
        _stop(first)


def test_the_display_is_usable():
    proc, display = browser.start_xvfb()
    try:
        probe = subprocess.run(["xdpyinfo", "-display", f":{display}"],
                               capture_output=True, text=True)
    finally:
        _stop(proc)
    if probe.returncode != 0 and "not found" in probe.stderr:
        pytest.skip("xdpyinfo not installed")
    assert probe.returncode == 0, probe.stderr
    assert "1600x1200" in probe.stdout


def test_an_xvfb_that_cannot_start_is_reported_with_its_own_error(monkeypatch):
    """Never a bare timeout: the reason Xvfb refused is what the caller needs."""
    real = subprocess.Popen

    def refuse(argv, *a, **kw):
        return real(["Xvfb", "-nosuchflag", *argv[1:]], *a, **kw)

    monkeypatch.setattr(browser.subprocess, "Popen", refuse)
    with pytest.raises(browser.MarionetteError) as caught:
        browser.start_xvfb(timeout=15)
    assert "never reported a display" in str(caught.value)
    assert "printed no error" not in str(caught.value)
