"""Step definitions for main module feature tests."""

import importlib
from unittest.mock import patch

from behave import given, then, when


@given("the CLI main function will return {code:d}")
def step_mock_main_return(context, code):
    """Mock the CLI main function to return a specific code."""
    context.mock_main_return = code


@when("I call the run function")
def step_call_run_function(context):
    """Call the run function."""
    with patch("cleveragents.__main__.main") as mock_main:
        mock_main.return_value = context.mock_main_return
        from cleveragents.__main__ import run

        context.run_result = run()


@then("the run function should return {code:d}")
def step_check_run_return(context, code):
    """Check the run function return value."""
    assert context.run_result == code


@given("the CLI main function will raise an exception")
def step_mock_main_exception(context):
    """Mock the CLI main function to raise an exception."""
    context.mock_main_exception = Exception("Test error")


@when("I call the run function expecting an exception")
def step_call_run_with_exception(context):
    """Call the run function expecting an exception."""
    context.exception_raised = False
    with patch("cleveragents.__main__.main") as mock_main:
        mock_main.side_effect = context.mock_main_exception
        from cleveragents.__main__ import run

        try:
            run()
        except Exception as e:
            context.exception_raised = True
            context.raised_exception = e


@then("an exception should be raised")
def step_check_exception_raised(context):
    """Check that an exception was raised."""
    assert context.exception_raised, "Expected exception was not raised"
    assert str(context.raised_exception) == "Test error"


@when("I import the __main__ module")
def step_import_main_module(context):
    """Import the __main__ module."""
    context.main_module = importlib.import_module("cleveragents.__main__")


@then('the module should have a "{attribute}" attribute')
def step_check_module_attribute(context, attribute):
    """Check that the module has a specific attribute."""
    assert hasattr(context.main_module, attribute), (
        f"Module missing {attribute} attribute"
    )


@then('the "{attribute}" attribute should be callable')
def step_check_attribute_callable(context, attribute):
    """Check that an attribute is callable."""
    attr = getattr(context.main_module, attribute)
    assert callable(attr), f"{attribute} is not callable"
