"""Step definitions for additional action CLI coverage."""

from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from behave import given, then, when

from cleveragents.application.services.plan_lifecycle_service import (
    PlanLifecycleService,
)
from cleveragents.cli.commands.action import _get_lifecycle_service


@given("a mocked container settings for action lifecycle")
def step_mock_container_settings(context) -> None:
    """Mock container to resolve lifecycle service via plan_lifecycle_service()."""
    context.settings = MagicMock()

    def _make_service() -> PlanLifecycleService:
        return PlanLifecycleService(settings=context.settings)

    container = SimpleNamespace(plan_lifecycle_service=_make_service)
    patcher = patch(
        "cleveragents.cli.commands.action.get_container",
        return_value=container,
    )
    patcher.start()
    context.container_patcher = patcher
    if not hasattr(context, "_cleanup_handlers"):
        context._cleanup_handlers = []
    context._cleanup_handlers.append(patcher.stop)


@when("I resolve the action lifecycle service")
def step_resolve_lifecycle_service(context) -> None:
    """Call the lifecycle service helper."""
    context.lifecycle_service = _get_lifecycle_service()


@when("I resolve the action lifecycle service twice")
def step_resolve_lifecycle_service_twice(context) -> None:
    """Call the lifecycle service helper twice."""
    context.lifecycle_services = [_get_lifecycle_service(), _get_lifecycle_service()]


@then("the lifecycle service should use container settings")
def step_assert_lifecycle_service_settings(context) -> None:
    """Verify the lifecycle service uses the mocked settings."""
    services = getattr(context, "lifecycle_services", None)
    if services is None:
        services = [context.lifecycle_service]
    for service in services:
        assert isinstance(service, PlanLifecycleService)
        assert service.settings is context.settings


@then("the lifecycle service instances should be distinct")
def step_assert_lifecycle_service_distinct(context) -> None:
    """Verify each lifecycle service instance is unique."""
    assert context.lifecycle_services[0] is not context.lifecycle_services[1]
