"""Step definitions for tui_settings_session_screens.feature."""

from behave import given, then, when

from cleveragents.tui.commands import TuiCommandRouter
from cleveragents.tui.screens.session_management import (
    SessionInfo,
    SessionManagementScreen,
)
from cleveragents.tui.screens.settings import SettingsScreen


# ---------------------------------------------------------------------------
# Background
# ---------------------------------------------------------------------------
@given("the TUI screens module is imported")
def step_tui_screens_imported(context):
    """Verify the screens module is importable."""
    assert SettingsScreen is not None
    assert SessionManagementScreen is not None
    assert SessionInfo is not None


# ---------------------------------------------------------------------------
# SettingsScreen scenarios
# ---------------------------------------------------------------------------
@given("a SettingsScreen widget")
def step_create_settings_screen(context):
    """Create a SettingsScreen widget."""
    context.settings_screen = SettingsScreen()


@given("a SettingsScreen widget that is visible")
def step_create_visible_settings_screen(context):
    """Create and show a SettingsScreen widget."""
    context.settings_screen = SettingsScreen()
    context.settings_screen.show()


@when("I show the settings screen")
def step_show_settings_screen(context):
    """Show the settings screen."""
    context.settings_screen.show()


@when("I hide the settings screen")
def step_hide_settings_screen(context):
    """Hide the settings screen."""
    context.settings_screen.hide()


@when("I navigate to the next setting")
def step_navigate_next_setting(context):
    """Navigate to the next setting."""
    context.settings_screen.navigate_next()


@when("I navigate to the previous setting")
def step_navigate_prev_setting(context):
    """Navigate to the previous setting."""
    context.settings_screen.navigate_prev()


@when('I set the theme to "{theme}"')
def step_set_theme(context, theme):
    """Set the theme."""
    context.settings_screen.set_theme(theme)


@when('I set the default_actor to "{actor}"')
def step_set_default_actor(context, actor):
    """Set the default actor."""
    context.settings_screen.set_default_actor(actor)


@when('I set the safety_level to "{level}"')
def step_set_safety_level(context, level):
    """Set the safety level."""
    context.settings_screen.set_safety_level(level)


@then('the theme should be "{expected}"')
def step_verify_theme(context, expected):
    """Verify the theme setting."""
    assert context.settings_screen.theme == expected


@then('the default_actor should be "{expected}"')
def step_verify_default_actor(context, expected):
    """Verify the default actor setting."""
    assert context.settings_screen.default_actor == expected


@then('the safety_level should be "{expected}"')
def step_verify_safety_level(context, expected):
    """Verify the safety level setting."""
    assert context.settings_screen.safety_level == expected


@then("the settings screen should be visible")
def step_verify_settings_visible(context):
    """Verify the settings screen is visible."""
    assert context.settings_screen.visible is True


@then("the settings screen should not be visible")
def step_verify_settings_not_visible(context):
    """Verify the settings screen is not visible."""
    assert context.settings_screen.visible is False


@then("the selected_index should be {index:d}")
def step_verify_selected_index(context, index):
    """Verify the selected index on whichever screen was created in this scenario."""
    screen = getattr(context, "session_screen", None) or getattr(
        context, "settings_screen", None
    )
    assert screen is not None, "no screen widget created in this scenario"
    assert screen.selected_index == index, (
        f"expected selected_index={index}, got {screen.selected_index}"
    )


# ---------------------------------------------------------------------------
# SessionManagementScreen scenarios
# ---------------------------------------------------------------------------
@given("a SessionManagementScreen widget")
def step_create_session_screen(context):
    """Create a SessionManagementScreen widget."""
    context.session_screen = SessionManagementScreen()


@given("a SessionManagementScreen widget with 3 sessions")
def step_create_session_screen_with_sessions(context):
    """Create a SessionManagementScreen widget with 3 sessions."""
    context.session_screen = SessionManagementScreen()
    sessions = [
        SessionInfo(
            session_id=f"session-{i}",
            name=f"Session {i}",
            message_count=i * 10,
            created_at="2026-04-19T00:00:00Z",
        )
        for i in range(3)
    ]
    context.session_screen.load_sessions(sessions, "session-0")


@when("I show the session management screen")
def step_show_session_screen(context):
    """Show the session management screen."""
    context.session_screen.show()


@when("I hide the session management screen")
def step_hide_session_screen(context):
    """Hide the session management screen."""
    context.session_screen.hide()


@when("I load {count:d} sessions")
def step_load_sessions(context, count):
    """Load sessions into the screen."""
    sessions = [
        SessionInfo(
            session_id=f"session-{i}",
            name=f"Session {i}",
            message_count=i * 10,
            created_at="2026-04-19T00:00:00Z",
        )
        for i in range(count)
    ]
    context.session_screen.load_sessions(sessions, "session-0")


@when("I navigate to the next session")
def step_navigate_next_session(context):
    """Navigate to the next session."""
    context.session_screen.navigate_next()


@when("I navigate to the previous session")
def step_navigate_prev_session(context):
    """Navigate to the previous session."""
    context.session_screen.navigate_prev()


@then("the sessions list should be empty")
def step_verify_sessions_empty(context):
    """Verify the sessions list is empty."""
    assert len(context.session_screen.sessions) == 0


@then("the sessions list should have {count:d} items")
def step_verify_sessions_count(context, count):
    """Verify the sessions list has the expected count."""
    assert len(context.session_screen.sessions) == count


@then('the current_session_id should be "{expected}"')
def step_verify_current_session_id(context, expected):
    """Verify the current session ID."""
    assert context.session_screen.current_session_id == expected


@then("the session management screen should be visible")
def step_verify_session_screen_visible(context):
    """Verify the session management screen is visible."""
    assert context.session_screen.visible is True


@then("the session management screen should not be visible")
def step_verify_session_screen_not_visible(context):
    """Verify the session management screen is not visible."""
    assert context.session_screen.visible is False


@then("get_selected_session should return a SessionInfo object")
def step_verify_selected_session_info(context):
    """Verify get_selected_session returns a SessionInfo object."""
    session = context.session_screen.get_selected_session()
    assert session is not None
    assert isinstance(session, SessionInfo)


@then("get_selected_session should return None")
def step_verify_selected_session_none(context):
    """Verify get_selected_session returns None."""
    session = context.session_screen.get_selected_session()
    assert session is None


@then(
    'get_settings should return theme "{theme}", default_actor "{actor}", '
    'safety_level "{level}"'
)
def step_verify_get_settings(context, theme, actor, level):
    """Verify get_settings returns the expected settings dict."""
    settings = context.settings_screen.get_settings()
    assert settings == {
        "theme": theme,
        "default_actor": actor,
        "safety_level": level,
    }


@then('the session screen rendered text should contain "{text}"')
def step_verify_session_rendered_text_contains(context, text):
    """Verify the rendered SessionManagementScreen text contains the given fragment."""
    assert text in context.session_screen._text, (
        f"expected {text!r} in rendered text, got: {context.session_screen._text!r}"
    )


# ---------------------------------------------------------------------------
# TuiCommandRouter /settings route scenarios
# ---------------------------------------------------------------------------
class _FakePersonaRegistry:
    """Minimal persona registry stub for /settings routing tests."""

    def list_personas(self):
        return []


class _FakePersonaState:
    """Minimal persona state stub for /settings routing tests."""

    def get_active(self, session_id):
        return None


@given("a TuiCommandRouter for settings tests")
def step_router_for_settings(context):
    """Create a TuiCommandRouter with minimal stubs for the /settings route."""
    context.router = TuiCommandRouter(
        persona_registry=_FakePersonaRegistry(),  # type: ignore[arg-type]
        persona_state=_FakePersonaState(),  # type: ignore[arg-type]
    )
