from __future__ import absolute_import

from pytest_xdist_tracker.tracker import TestRunner, TestTracker


def pytest_addoption(parser):
    """
    Command line options for our plugin
    Parameters
    ----------
    parser: _pytest.config.Parser
    """
    group = parser.getgroup("xdist_tracker")
    group.addoption(
        "--xdist-stats",
        action="store",
        default="xdist_stats",
        dest="xdist_stats",
        help=(
            "File pattern to save tests which were run on the xdist node (by default %(default)s). "
            "As result if will run with `-n2` will generated 2 artefacts like:"
            "xdist_stats_worker_gw0.txt and xdist_stats_worker_gw1.txt"
        ),
    )
    group.addoption(
        "--from-xdist-stats",
        action="store",
        default=None,
        dest="from_xdist_stats",
        help=(
            "File (generated by `--xdist-stats`) with tests(nodeid) to run in single thread, "
            "could be helpful to reproduce issues "
            "related to coupled tests which corrupted or doesn't clear some state after self "
            "(not work with xdist `-n`)"
        ),
    )


def pytest_configure(config):
    """
    Enable this reporter when tests run with XDIST
    """
    is_run_with_xdist = bool(
        config.pluginmanager.get_plugin("xdist") and config.option.numprocesses
    )
    is_run_xdist_worker = bool(getattr(config, "workerinput", None))
    is_run_to_reproduce = bool(config.getoption("--from-xdist-stats"))
    if (is_run_with_xdist or is_run_xdist_worker) and not is_run_to_reproduce:
        reporter = TestTracker(config)
        config.pluginmanager.register(reporter, name="xdist_tracker")
    if is_run_to_reproduce and not (is_run_with_xdist or is_run_xdist_worker):
        runner = TestRunner(config)
        config.pluginmanager.register(runner, name="xdist_runner")
