"""
Command line argument handling
==============================

**Module:** ``tests.plugin.test_cmd_line``
"""

from pathlib import Path
from typing import Callable

import pytest
from _pytest.pytester import Pytester

from _ptcsvp.cmdline import HELP_TEXT


@pytest.mark.parametrize(
    ["base_dir"],
    [
        (True,),
        (False,),
    ],
)
def test_base_dir_param(
    pytester: Pytester,
    base_dir: bool,
    simple_test_csv: str,
    simple_fruit_test: Callable[[str], str],
) -> None:
    """
    Test if the ``--csv-params-base-dir`` command line argument is valued. For laziness, it uses a poor parametrization.

    :param pytester: Pytester fixture
    :param base_dir: Shall the base dir parameter be set?
    :param simple_test_csv: Fixture :meth:`~tests.plugin.conftest.simple_test_csv`
    :param simple_fruit_test: Fixture :meth:`~tests.plugin.conftest.simple_fruit_test`
    """

    csv_file = str(pytester.makefile(".csv", simple_test_csv).absolute())

    parameters = ["-p", "no:bandit"]
    if base_dir:
        path = Path(csv_file)
        parameters.extend(["--csv-params-base-dir", str(path.parent.absolute())])
        csv_file = path.name

    pytester.makepyfile(simple_fruit_test(csv_file))

    result = pytester.runpytest(*parameters)
    result.assert_outcomes(passed=3, failed=1)


def test_help(pytester: Pytester) -> None:
    """
    Test that the pytest help now contains our command line argument with our help text.

    :param pytester: Pytester fixture
    """

    result = pytester.runpytest("--help")
    index_csv_params = -1
    index_minus_minus = -1
    index_help = -1

    for index, line in enumerate(result.stdout.lines):
        if "csv-params:" in line and index_csv_params < 0:
            index_csv_params = index
            continue
        if "--csv-params-base-dir" in line and index_minus_minus < 0:
            index_minus_minus = index
        if HELP_TEXT in line and index_help < 0:
            index_help = index

    assert index_csv_params >= 0
    assert index_csv_params < index_minus_minus <= index_help
