import importlib

import pytest

pytest.importorskip("click")

from click.testing import CliRunner


def _load_cli():
    cli_module = importlib.import_module("gjalla_precommit.cli")
    return cli_module.main


def test_init_command_recognized():
    main = _load_cli()
    assert "init" in main.commands


def test_setup_command_recognized():
    main = _load_cli()
    assert "setup" in main.commands


def test_check_command_recognized():
    main = _load_cli()
    assert "check" in main.commands


def test_status_command_recognized():
    main = _load_cli()
    assert "status" in main.commands


def test_mcp_install_recognized():
    main = _load_cli()
    assert "mcp" in main.commands
    assert "install" in main.commands["mcp"].commands


def test_unknown_command_shows_help():
    main = _load_cli()
    runner = CliRunner()
    result = runner.invoke(main, ["unknown"])
    assert result.exit_code != 0
    assert "No such command" in result.output


def test_help_flag_shows_help():
    main = _load_cli()
    runner = CliRunner()
    result = runner.invoke(main, ["--help"])
    assert result.exit_code == 0
    assert "Usage" in result.output


def test_version_flag_shows_version():
    main = _load_cli()
    runner = CliRunner()
    result = runner.invoke(main, ["--version"])
    assert result.exit_code == 0
    assert "gjalla" in result.output.lower()


def test_auth_command_recognized():
    main = _load_cli()
    assert "auth" in main.commands


def test_auth_with_key_flag():
    main = _load_cli()
    params = {param.name: param for param in main.commands["auth"].params}
    assert "key" in params


def test_auth_via_env_var(monkeypatch):
    settings = importlib.import_module("gjalla_precommit.config.settings")
    monkeypatch.setenv("GJALLA_API_KEY", "gj_env_key")
    assert settings.get_api_key() == "gj_env_key"
