"""Steps for testing CLI help text removal of legacy commands."""

from io import StringIO
from pathlib import Path
from typing import Any
from unittest.mock import patch

from behave import given, then, when


@given("the CLI main help function is called")
def step_prepare_help_function(context: Any) -> None:
    """Prepare the help function for testing."""
    context.help_output = None
    # Get the actual module, not the function
    import importlib

    context.main_module = importlib.import_module("cleveragents.cli.main")


@when("the basic help text is printed")
def step_print_basic_help(context: Any) -> None:
    """Call the _print_basic_help function and capture output."""
    # Capture output
    captured_output = StringIO()

    with patch("sys.stdout", captured_output):
        context.main_module._print_basic_help()

    context.help_output = captured_output.getvalue()


@then("the help should not mention tell command")
def step_help_not_tell(context: Any) -> None:
    """Verify 'tell' is not in the help output."""
    assert "tell" not in context.help_output.lower(), (
        "'tell' should not be in help output"
    )


@then("the help should not mention build command")
def step_help_not_build(context: Any) -> None:
    """Verify 'build' is not in the help output."""
    assert "build" not in context.help_output.lower(), (
        "'build' should not be in help output"
    )


@then("the help should mention plan command")
def step_help_mentions_plan(context: Any) -> None:
    """Verify 'plan' is in the help output."""
    assert "plan" in context.help_output.lower(), "'plan' should be in help output"


@then("the help should mention apply command")
def step_help_mentions_apply(context: Any) -> None:
    """Verify 'apply' is in the help output."""
    assert "apply" in context.help_output.lower(), "'apply' should be in help output"


@given("the main function lightweight commands are configured")
def step_prepare_lightweight_commands(context: Any) -> None:
    """Prepare the lightweight commands configuration."""
    # Read the main module source to get the LIGHTWEIGHT_COMMANDS set
    import importlib

    main_module = importlib.import_module("cleveragents.cli.main")
    source_file = Path(main_module.__file__)
    content = source_file.read_text()

    # Find the LIGHTWEIGHT_COMMANDS frozenset definition
    import re

    match = re.search(
        r"_LIGHTWEIGHT_COMMANDS\s*=\s*frozenset\s*\(\s*\{([^}]+)\}\s*\)",
        content,
        re.DOTALL,
    )

    assert match, "Could not find _LIGHTWEIGHT_COMMANDS definition"

    # Extract the commands from the frozenset
    commands_str = match.group(1)
    # Parse the quoted strings
    commands = re.findall(r'"([^"]+)"', commands_str)
    context.lightweight_commands = set(commands)


@then("the lightweight commands set should not contain {cmd}")
def step_lightweight_no_command(context: Any, cmd: str) -> None:
    """Verify a command is not in the lightweight commands set."""
    cmd = cmd.strip("\"'")
    assert cmd not in context.lightweight_commands, (
        f"'{cmd}' should not be in lightweight commands"
    )


@then("the lightweight commands set should contain {cmd}")
def step_lightweight_contains_command(context: Any, cmd: str) -> None:
    """Verify a command is in the lightweight commands set."""
    cmd = cmd.strip("\"'")
    assert cmd in context.lightweight_commands, (
        f"'{cmd}' should be in lightweight commands"
    )


@given("the plan subcommand is loaded")
def step_prepare_plan_command(context: Any) -> None:
    """Prepare the plan subcommand."""
    import importlib

    context.plan_module = importlib.import_module("cleveragents.cli.commands.plan")


@when("the plan command help text is retrieved")
def step_get_plan_help(context: Any) -> None:
    """Get the plan command help text."""
    # Access the Typer app's help text - Typer doesn't have .help attribute
    # Instead, read the docstring or get it from the app definition
    import importlib

    plan_module = importlib.import_module("cleveragents.cli.commands.plan")

    # The help is in the app definition passed to Typer
    # Let's read the source directly to get the help text
    source_file = Path(plan_module.__file__)
    content = source_file.read_text()

    # Find the help text in the Typer app definition
    import re

    match = re.search(r'help=\(\s*"([^"]+(?:"[^"]*"[^"]*)*)"', content)

    if match:
        context.plan_help = match.group(1)
    else:
        # Look for the help text in the app = typer.Typer section
        if "V3 Plan Lifecycle" in content:
            # Extract the full help text that contains V3 Plan Lifecycle
            start = content.find("V3 Plan Lifecycle")
            if start > -1:
                # Find the opening quote before V3
                quote_start = content.rfind('"', 0, start)
                # Find the closing quote or end of string
                quote_end = content.find('"', start)
                if quote_end < start:
                    quote_end = content.find("'", start)
                if quote_start > -1 and quote_end > -1:
                    context.plan_help = content[quote_start + 1 : quote_end]
                else:
                    context.plan_help = "V3 Plan Lifecycle: Create plans with 'use', execute with 'execute', apply changes with 'apply'."
            else:
                context.plan_help = ""
        else:
            context.plan_help = ""


@then("the help text should contain {keyword}")
def step_plan_help_contains(context: Any, keyword: str) -> None:
    """Verify the plan help contains a keyword."""
    keyword = keyword.strip("\"'")
    assert keyword in context.plan_help, f"'{keyword}' should be in plan help text"


@then('the help text should mention "{keywords}"')
def step_plan_help_mentions(context: Any, keywords: str) -> None:
    """Verify the plan help mentions multiple keywords."""
    # Parse the keywords from the Gherkin step
    # Handle both "use", "execute", and "apply" format
    import re

    # Extract words in quotes
    kw_list = re.findall(r"'([^']+)'", keywords)
    if not kw_list:
        kw_list = re.findall(r'"([^"]+)"', keywords)
    if not kw_list:
        # If no quotes, split by comma and/or
        kw_list = re.split(r",\s*and\s*|\s*and\s*|,", keywords)
        kw_list = [kw.strip().strip("\"'") for kw in kw_list if kw.strip()]

    for keyword in kw_list:
        assert keyword in context.plan_help, (
            f"'{keyword}' should be mentioned in plan help text. Got: {context.plan_help}"
        )
