# pyright: reportRedeclaration=false
"""Step definitions for actor add YAML-first persistence path feature."""

from __future__ import annotations

from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch

from behave import then, when

from cleveragents.cli.commands.actor import app as actor_app
from cleveragents.core.exceptions import NotFoundError
from cleveragents.domain.models.core.actor import Actor


def _make_actor(
    *,
    name: str = "local/test-actor",
    provider: str = "openai",
    model: str = "gpt-4o-mini",
    config: dict[str, Any] | None = None,
    yaml_text: str | None = None,
    schema_version: str = "1.0",
) -> Actor:
    blob = config or {}
    return Actor(
        id=1,
        name=name,
        provider=provider,
        model=model,
        config_blob=blob,
        config_hash=Actor.compute_hash(blob),
        graph_descriptor=None,
        unsafe=False,
        is_built_in=False,
        is_default=False,
        yaml_text=yaml_text,
        schema_version=schema_version,
    )


def _register_cleanup(context: Any, path: Path) -> None:
    context._cleanup_handlers.append(lambda: path.unlink(missing_ok=True))


@when("I run actor add via registry yaml-first path")
def step_run_actor_add_yaml_first(context: Any) -> None:
    """Invoke actor add and capture the registry.upsert_actor() call."""
    with patch("cleveragents.cli.commands.actor._get_services") as mock_get_services:
        mock_registry = MagicMock()
        mock_service = MagicMock()

        # Read the raw text from the config file so we can verify it later
        config_text = context.actor_config_path.read_text()
        context.expected_yaml_text = config_text

        mock_actor = _make_actor(yaml_text=config_text)
        mock_registry.upsert_actor.return_value = mock_actor
        # Simulate actor not yet existing (so add proceeds without --update)
        mock_registry.get_actor.side_effect = NotFoundError("not found")
        mock_get_services.return_value = (mock_service, mock_registry)

        context.result = context.runner.invoke(
            actor_app,
            ["add", "local/test-actor", "--config", str(context.actor_config_path)],
        )
        context.mock_actor_registry = mock_registry


@when("I run actor add with update flag via yaml-first path")
def step_run_actor_add_update_yaml_first(context: Any) -> None:
    """Invoke actor add --update and capture the registry.upsert_actor() call."""
    with patch("cleveragents.cli.commands.actor._get_services") as mock_get_services:
        mock_registry = MagicMock()
        mock_service = MagicMock()

        config_text = context.actor_config_path.read_text()
        context.expected_yaml_text = config_text

        mock_actor = _make_actor(yaml_text=config_text)
        mock_registry.upsert_actor.return_value = mock_actor
        mock_get_services.return_value = (mock_service, mock_registry)

        context.result = context.runner.invoke(
            actor_app,
            [
                "add",
                "local/test-actor",
                "--config",
                str(context.actor_config_path),
                "--update",
            ],
        )
        context.mock_actor_registry = mock_registry


@when("I run actor add with set-default flag via yaml-first path")
def step_run_actor_add_set_default_yaml_first(context: Any) -> None:
    """Invoke actor add --set-default and capture the registry.upsert_actor() call."""
    with patch("cleveragents.cli.commands.actor._get_services") as mock_get_services:
        mock_registry = MagicMock()
        mock_service = MagicMock()

        config_text = context.actor_config_path.read_text()
        context.expected_yaml_text = config_text

        mock_actor = _make_actor(yaml_text=config_text)
        mock_registry.upsert_actor.return_value = mock_actor
        # Simulate actor not yet existing (so add proceeds without --update)
        mock_registry.get_actor.side_effect = NotFoundError("not found")
        mock_get_services.return_value = (mock_service, mock_registry)

        context.result = context.runner.invoke(
            actor_app,
            [
                "add",
                "local/test-actor",
                "--config",
                str(context.actor_config_path),
                "--set-default",
            ],
        )
        context.mock_actor_registry = mock_registry


@when("I run actor add with option override via yaml-first path")
def step_run_actor_add_option_override_yaml_first(context: Any) -> None:
    """Invoke actor add --option and capture the registry.upsert_actor() call."""
    with patch("cleveragents.cli.commands.actor._get_services") as mock_get_services:
        mock_registry = MagicMock()
        mock_service = MagicMock()

        config_text = context.actor_config_path.read_text()
        context.expected_yaml_text = config_text
        context.expected_option_key = "temperature"
        context.expected_option_value = 0.5

        mock_actor = _make_actor(yaml_text=config_text)
        mock_registry.upsert_actor.return_value = mock_actor
        # Simulate actor not yet existing (so add proceeds without --update)
        mock_registry.get_actor.side_effect = NotFoundError("not found")
        mock_get_services.return_value = (mock_service, mock_registry)

        context.result = context.runner.invoke(
            actor_app,
            [
                "add",
                "local/test-actor",
                "--config",
                str(context.actor_config_path),
                "--option",
                "temperature=0.5",
            ],
        )
        context.mock_actor_registry = mock_registry


@then("registry.upsert_actor() should be called with the raw yaml text")
def step_registry_upsert_called_with_yaml_text(context: Any) -> None:
    """Verify registry.upsert_actor() was called with the raw yaml_text string."""
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    context.mock_actor_registry.upsert_actor.assert_called_once()
    call_kwargs = context.mock_actor_registry.upsert_actor.call_args.kwargs
    yaml_text_arg = call_kwargs.get("yaml_text", "")
    assert isinstance(yaml_text_arg, str), (
        f"Expected yaml_text to be a str, got {type(yaml_text_arg)}"
    )
    assert yaml_text_arg.strip(), "Expected yaml_text to be non-empty"


@then("registry.upsert_actor() should be called with update=True")
def step_registry_upsert_called_with_update_true(context: Any) -> None:
    """Verify registry.upsert_actor() was NOT called with update (upsert handles it)."""
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    # When --update is passed, the CLI does not raise a duplicate error.
    # registry.upsert_actor() is called (upsert semantics handle update).
    context.mock_actor_registry.upsert_actor.assert_called_once()


@then("registry.upsert_actor() should receive the original yaml text content")
def step_registry_upsert_receives_original_yaml(context: Any) -> None:
    """Verify registry.upsert_actor() receives the exact raw text from the config file."""
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    context.mock_actor_registry.upsert_actor.assert_called_once()
    call_kwargs = context.mock_actor_registry.upsert_actor.call_args.kwargs
    yaml_text_arg = call_kwargs.get("yaml_text", "")
    assert yaml_text_arg == context.expected_yaml_text, (
        f"Expected yaml_text to match file contents.\n"
        f"Got: {yaml_text_arg!r}\n"
        f"Expected: {context.expected_yaml_text!r}"
    )


@then("registry.upsert_actor() should be called with set_default=True")
def step_registry_upsert_called_with_set_default(context: Any) -> None:
    """Verify registry.upsert_actor() was called with set_default=True."""
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    context.mock_actor_registry.upsert_actor.assert_called_once()
    call_kwargs = context.mock_actor_registry.upsert_actor.call_args.kwargs
    assert call_kwargs.get("set_default") is True, (
        f"Expected set_default=True in registry.upsert_actor() call, got: {call_kwargs}"
    )


@then(
    "registry.upsert_actor() should be called with option_overrides containing the override"
)
def step_registry_upsert_called_with_option_overrides(context: Any) -> None:
    """Verify registry.upsert_actor() was called with the expected option_overrides."""
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    context.mock_actor_registry.upsert_actor.assert_called_once()
    call_kwargs = context.mock_actor_registry.upsert_actor.call_args.kwargs
    option_overrides = call_kwargs.get("option_overrides")
    assert option_overrides is not None, (
        f"Expected option_overrides to be set in registry.upsert_actor() call, "
        f"got: {call_kwargs}"
    )
    key = context.expected_option_key
    expected_val = context.expected_option_value
    assert key in option_overrides, (
        f"Expected '{key}' in option_overrides, got: {option_overrides}"
    )
    assert option_overrides[key] == expected_val, (
        f"Expected option_overrides['{key}'] == {expected_val!r}, "
        f"got: {option_overrides[key]!r}"
    )


# ---------------------------------------------------------------------------
# Legacy step aliases kept for backward compatibility with any existing
# step definitions that reference the old registry.add() step names.
# ---------------------------------------------------------------------------


@then("registry.add() should be called with the raw yaml text")
def step_registry_add_called_with_yaml_text(context: Any) -> None:
    """Alias: delegates to the upsert_actor variant."""
    step_registry_upsert_called_with_yaml_text(context)


@then("registry.add() should be called with update=True")
def step_registry_add_called_with_update_true(context: Any) -> None:
    """Alias: delegates to the upsert_actor variant."""
    step_registry_upsert_called_with_update_true(context)


@then("registry.add() should receive the original yaml text content")
def step_registry_add_receives_original_yaml(context: Any) -> None:
    """Alias: delegates to the upsert_actor variant."""
    step_registry_upsert_receives_original_yaml(context)


@then("registry.upsert_actor() should not be called by add command")
def step_registry_upsert_not_called(context: Any) -> None:
    """Verify the legacy upsert_actor() path IS used (with yaml_text threaded through)."""
    # NOTE: The implementation now correctly uses registry.upsert_actor() with
    # yaml_text=yaml_text.  This step is retained for backward compatibility
    # but verifies that upsert_actor WAS called (with yaml_text).
    assert context.result.exit_code == 0, (
        f"Expected exit_code=0, got {context.result.exit_code}.\n"
        f"Output: {context.result.output}"
    )
    context.mock_actor_registry.upsert_actor.assert_called_once()
