"""Step definitions for TDD Issue #554 — session list DI regression tests.

These steps exercise the *real* DI path in ``_get_session_service()``.
Bug #554 has been fixed: the DI container now provides a
``session_service`` provider that builds the service correctly.
"""

from __future__ import annotations

from behave import then, when
from behave.runner import Context

from cleveragents.cli.commands import session as session_mod
from cleveragents.cli.commands.session import app as session_app
from cleveragents.domain.models.core.session import SessionService

# The "Given a CLI runner using the real session DI path" step and the
# parameterised exit/JSON assertion steps live in tdd_session_shared_steps.py
# (Behave loads all steps globally).


@when("I invoke the session list command")
def step_invoke_list(context: Context) -> None:
    """Invoke ``session list`` through the real CLI app."""
    context.result = context.runner.invoke(session_app, ["list"])


@when("I request the session service from the DI container")
def step_request_service(context: Context) -> None:
    """Call ``_get_session_service()`` directly to test the DI wiring."""
    try:
        context.session_service = session_mod._get_session_service()
        context.service_error = None
    except AttributeError as exc:
        context.session_service = None
        context.service_error = exc


@when("I invoke the session list command with format json")
def step_invoke_list_json(context: Context) -> None:
    """Invoke ``session list --format json`` through the real CLI app."""
    context.result = context.runner.invoke(session_app, ["list", "--format", "json"])


@then("the session service should be a valid SessionService instance")
def step_service_is_valid(context: Context) -> None:
    """Assert that ``_get_session_service()`` returned a usable service."""
    assert context.service_error is None, (
        f"_get_session_service() raised {context.service_error!r}"
    )
    assert isinstance(context.session_service, SessionService), (
        f"Expected SessionService, got {type(context.session_service)}"
    )
