"""Unit tests for the ai-org CLI entry point."""

from unittest.mock import patch

import pytest
from click.testing import CliRunner

from ai_org.cli import cli, main


@pytest.fixture
def runner():
    """Create a Click test runner."""
    return CliRunner()


@pytest.mark.unit
def test_cli_help(runner):
    """Invoking --help should exit 0 and show the program description."""
    result = runner.invoke(cli, ["--help"])
    assert result.exit_code == 0
    assert "AI-ORG" in result.output


@pytest.mark.unit
def test_cli_version(runner):
    """Invoking --version should print the version string."""
    result = runner.invoke(cli, ["--version"])
    assert result.exit_code == 0
    assert "ai-org" in result.output


@pytest.mark.unit
def test_cli_no_command_shows_help(runner):
    """Invoking with no arguments should display help text."""
    result = runner.invoke(cli, [])
    assert result.exit_code == 0
    assert "AI-ORG" in result.output


@pytest.mark.unit
def test_cli_json_flag(runner):
    """The --json flag should be stored in the Click context."""
    result = runner.invoke(cli, ["--json"])
    assert result.exit_code == 0


@pytest.mark.unit
def test_cli_debug_flag(runner):
    """The --debug flag should be accepted without error."""
    result = runner.invoke(cli, ["--debug"])
    assert result.exit_code == 0


@pytest.mark.unit
def test_cli_profile_option(runner):
    """The --profile option should be accepted."""
    result = runner.invoke(cli, ["--profile", "test"])
    assert result.exit_code == 0


@pytest.mark.unit
def test_cli_region_option(runner):
    """The --region option should be accepted."""
    result = runner.invoke(cli, ["--region", "eu-west-1"])
    assert result.exit_code == 0


@pytest.mark.unit
def test_cli_unknown_command(runner):
    """An unknown subcommand should produce a non-zero exit code."""
    result = runner.invoke(cli, ["nonexistent"])
    assert result.exit_code != 0


@pytest.mark.unit
def test_main_returns_zero():
    """main() should return 0 when cli() succeeds."""
    with patch("ai_org.cli.cli") as mock_cli:
        mock_cli.return_value = None
        assert main() == 0


@pytest.mark.unit
def test_main_handles_click_exception():
    """main() should return 1 when cli() raises a ClickException."""
    from click import ClickException

    with patch("ai_org.cli.cli", side_effect=ClickException("boom")):
        assert main() == 1


@pytest.mark.unit
def test_main_handles_keyboard_interrupt():
    """main() should return 130 on KeyboardInterrupt."""
    with patch("ai_org.cli.cli", side_effect=KeyboardInterrupt):
        assert main() == 130
