"""Steps for testing MCP logger finally block cleanup in session CLI commands."""

from pathlib import Path
from typing import Any

from behave import given, then, when

import cleveragents.cli.commands.session as session_module


@given("the session create function initializes mcp_logger from logging module")
def step_check_create_initializes_logger(context: Any) -> None:
    """Verify the create function initializes mcp_logger."""
    # Read the source file to verify mcp_logger initialization
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Check that the create function has mcp_logger initialization
    assert "mcp_logger = logging.getLogger" in content, (
        "mcp_logger not initialized in create function"
    )
    context.create_has_logger_init = True


@given("the session list function initializes mcp_logger from logging module")
def step_check_list_initializes_logger(context: Any) -> None:
    """Verify the list function initializes mcp_logger."""
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Check that the list_sessions function has mcp_logger initialization
    assert "mcp_logger = logging.getLogger" in content, (
        "mcp_logger not initialized in list_sessions function"
    )
    context.list_has_logger_init = True


@given("the session create function with format-dependent suppression")
def step_create_has_format_check(context: Any) -> None:
    """Verify the create function has format-dependent suppression."""
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Check for format-dependent logic
    assert (
        "if fmt not in (OutputFormat.RICH.value, OutputFormat.COLOR.value)" in content
    ), "create function missing format check for suppression"
    assert "mcp_logger.setLevel(logging.CRITICAL)" in content, (
        "create function missing CRITICAL level setting"
    )
    context.create_has_format_check = True


@given("the session list function with format-dependent suppression")
def step_list_has_format_check(context: Any) -> None:
    """Verify the list function has format-dependent suppression."""
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Check for format-dependent logic in list_sessions
    assert (
        "if fmt not in (OutputFormat.RICH.value, OutputFormat.COLOR.value)" in content
    ), "list_sessions function missing format check for suppression"
    assert "mcp_logger.setLevel(logging.CRITICAL)" in content, (
        "list_sessions function missing CRITICAL level setting"
    )
    context.list_has_format_check = True


@when("the session create command is executed with JSON format")
def step_execute_create_json(context: Any) -> None:
    """Simulate executing create with JSON format."""
    # Store format for later assertions
    context.test_format = "json"
    context.is_rich_format = False


@when("the session list command is executed with JSON format")
def step_execute_list_json(context: Any) -> None:
    """Simulate executing list with JSON format."""
    context.test_format = "json"
    context.is_rich_format = False


@when('format is "{fmt}"')
def step_set_format(context: Any, fmt: str) -> None:
    """Set the current format being tested."""
    context.test_format = fmt
    context.is_rich_format = fmt in ("rich", "color")


@then("the mcp_logger.setLevel should be called to restore orig_level")
def step_verify_restore_logic(context: Any) -> None:
    """Verify that setLevel is called to restore original level."""
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Check for the finally block that restores the level
    assert "finally:" in content, "Missing finally block"
    assert "mcp_logger.setLevel(orig_level)" in content, (
        "Missing restoration of original mcp_logger level in finally block"
    )


@then("the finally block ensures restoration even on success")
def step_verify_finally_block_structure(context: Any) -> None:
    """Verify the finally block structure is correct."""
    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Get the content around the finally block
    assert "finally:" in content, "No finally block found"

    # Extract the part after "finally:" to verify it has setLevel
    finally_idx = content.find("finally:")
    assert finally_idx > -1, "Could not find finally block"

    # Check the next few lines after finally
    after_finally = content[finally_idx : finally_idx + 300]
    assert "mcp_logger.setLevel" in after_finally, (
        "Logger restoration not found in finally block"
    )


@then("MCP logger should be set to CRITICAL level")
def step_verify_critical_level_set(context: Any) -> None:
    """Verify that MCP logger is set to CRITICAL for non-rich formats."""
    if not context.is_rich_format:
        source_file = Path(session_module.__file__)
        content = source_file.read_text()

        # Check for CRITICAL level setting
        assert "mcp_logger.setLevel(logging.CRITICAL)" in content, (
            "MCP logger not set to CRITICAL level"
        )


@then("MCP logger should NOT be set to CRITICAL level")
def step_verify_not_critical_for_rich(context: Any) -> None:
    """Verify that MCP logger is NOT set to CRITICAL for rich/color formats."""
    # For rich/color formats, the code should skip the setLevel(CRITICAL) call
    assert context.is_rich_format, "This step only applies to rich/color formats"

    source_file = Path(session_module.__file__)
    content = source_file.read_text()

    # Verify the conditional exists
    assert (
        "if fmt not in (OutputFormat.RICH.value, OutputFormat.COLOR.value):" in content
    ), "Missing format check that excludes rich/color formats"
