"""Step definitions for module entry points."""

import sys
from unittest.mock import patch

from behave import given, then, when


@when("I execute the __main__ module")
def step_execute_main_module(context):
    """Execute the __main__ module."""
    try:
        from cleveragents import __main__

        context.main_module = __main__
        context.module_error = None
    except Exception as e:
        context.module_error = e
        context.main_module = None


@then("the CLI should start")
def step_cli_starts(context):
    """Verify the CLI starts."""
    assert context.module_error is None, f"Module import failed: {context.module_error}"
    assert context.main_module is not None
    assert hasattr(context.main_module, "run")


# Step already defined in main_module_steps.py


@then("it should have a run function")
def step_has_run_function(context):
    """Verify the module has a run function."""
    # Handle both ways the module might be set
    if not hasattr(context, "module_error"):
        context.module_error = None

    assert context.module_error is None, f"Module import failed: {context.module_error}"
    assert context.main_module is not None
    assert hasattr(context.main_module, "run")
    assert callable(context.main_module.run)


@when("I call ensure_cli_importable")
def step_call_ensure_cli_importable(context):
    """Call ensure_cli_importable."""
    from cleveragents.platform import ensure_cli_importable

    context.cli_module = ensure_cli_importable()


@then("it should return the CLI module")
def step_return_cli_module(context):
    """Verify CLI module is returned."""
    assert context.cli_module is not None
    assert context.cli_module.__name__ == "cleveragents.cli"


@then("the module should have a cli attribute")
def step_module_has_cli(context):
    """Verify module has cli attribute."""
    assert hasattr(context.cli_module, "cli")


@then("the module should have a main attribute")
def step_module_has_main(context):
    """Verify module has main attribute."""
    assert hasattr(context.cli_module, "main")


@given("the CLI module is already imported")
@when("the CLI module is already imported")
def step_cli_already_imported(context):
    """Ensure CLI module is already imported."""

    assert "cleveragents.cli" in sys.modules
    context.already_imported = True


@then("it should return the cached module")
def step_return_cached_module(context):
    """Verify cached module is returned."""
    assert context.cli_module is not None
    assert context.cli_module.__name__ == "cleveragents.cli"
    assert context.already_imported


@when("the CLI module import fails")
def step_cli_import_fails(context):
    """Mock CLI module import to fail."""
    context.import_should_fail = True


@then("it should propagate the import error")
def step_propagate_import_error(context):
    """Verify import error is propagated."""
    # Since we can't easily mock the import when the module is already loaded,
    # we'll test the behavior by mocking ensure_cli_importable directly

    with patch(
        "cleveragents.platform.ensure_cli_importable",
        side_effect=ImportError("Test import error"),
    ):
        try:
            from cleveragents.platform import ensure_cli_importable

            ensure_cli_importable()
            raise AssertionError("Expected ImportError was not raised")
        except ImportError as e:
            assert "Test import error" in str(e)
