from importlib.metadata import version

import pytest

from examples import click_process, click_subcommand
from shtab.main import main

from .test_shtab import no_log_info  # noqa: F401, pylint: disable=unused-import, yapf: disable
from .test_shtab import fix_shell

ARG_HELP = version('click') >= '8.5'


@pytest.fixture
def runner():
    pytest.importorskip('click')
    from click import testing
    return testing.CliRunner()


@fix_shell
def test_main(shell, capsys):
    main(['-us', shell, 'examples.click_subcommand.main'])
    captured = capsys.readouterr()
    assert "# AUTOMATICALLY GENERATED by https://github.com/tqdm/shtab" in captured.out
    assert not captured.err


@fix_shell
def test_plain(shell, runner):
    result = runner.invoke(click_process.process, ['.'])
    assert result.output == "Reading from None and writing to .\n"
    assert result.exit_code == 0
    result = runner.invoke(click_process.process, ['--print-completion', shell])
    assert "# AUTOMATICALLY GENERATED by https://github.com/tqdm/shtab" in result.output
    assert result.exit_code == 0


@fix_shell
def test_rootcmd(shell, runner):
    result = runner.invoke(click_subcommand.main, ['process', '.'])
    assert result.output == "Reading from None and writing to .\n"
    assert result.exit_code == 0
    result = runner.invoke(click_subcommand.main, ['completion', shell])
    assert "# AUTOMATICALLY GENERATED by https://github.com/tqdm/shtab" in result.output
    assert result.exit_code == 0
