"""Set test env vars before the pygitweb package is imported (see pygitweb/conftest.py)."""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import pytest

_test_auth_config = Path(os.environ.get("TEMP", "/tmp")) / "pygitweb-test-auth.json"
_test_settings_config = Path(os.environ.get("TEMP", "/tmp")) / "pygitweb-test-settings.json"
os.environ.setdefault("PYGITWEB_AUTH", "0")
os.environ.setdefault("PYGITWEB_AUTH_CONFIG", str(_test_auth_config))
os.environ.setdefault("PYGITWEB_SETTINGS_CONFIG", str(_test_settings_config))


def pytest_addoption(parser: pytest.Parser) -> None:
    parser.addoption(
        "--js-tests",
        action="store_true",
        default=False,
        help="Run JavaScript unit tests (requires the playwright group and Chromium)",
    )
    parser.addoption(
        "--playwright",
        action="store_true",
        default=False,
        help="Run browser integration tests (requires the playwright group)",
    )


def pytest_configure(config: pytest.Config) -> None:
    if not config.getoption("--playwright"):
        return
    subprocess.run(
        [sys.executable, "-m", "playwright", "install", "chromium"],
        check=True,
    )


def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
    skip_js = None
    if not config.getoption("--js-tests"):
        skip_js = pytest.mark.skip(reason="JS tests are off by default; pass --js-tests to run them")
    skip_playwright = None
    if not config.getoption("--playwright"):
        skip_playwright = pytest.mark.skip(reason="Playwright tests are off by default; pass --playwright to run them")
    for item in items:
        if skip_js is not None and "static_tests" in item.path.parts:
            item.add_marker(skip_js)
        if skip_playwright is not None and "integration" in item.path.parts:
            item.add_marker(skip_playwright)