"""Tests for the task tools — log_work in particular wires into the
consolidation pipeline after every successful log."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch


async def test_log_work_tool_invokes_maybe_consolidate():
    """log_work must call maybe_consolidate(user_id, task_id, reason='log_added')
    after a successful task_logs.create_log."""
    from fabledassistant.services.tools import tasks as tasks_tool

    fake_task = SimpleNamespace(id=42, title="X", status="in_progress")
    fake_log = SimpleNamespace(
        to_dict=lambda: {"id": 1, "content": "did stuff"},
    )

    # get_note_by_title is imported at the top of tools/tasks.py — patch the
    # consumer module's bound symbol, not the source.
    with patch(
        "fabledassistant.services.tools.tasks.get_note_by_title",
        new=AsyncMock(return_value=fake_task),
    ), patch(
        "fabledassistant.services.task_logs.create_log",
        new=AsyncMock(return_value=fake_log),
    ), patch(
        "fabledassistant.services.consolidation.maybe_consolidate",
        new=AsyncMock(),
    ) as mock_mc:
        result = await tasks_tool.log_work_tool(
            user_id=1, arguments={"task": "X", "content": "did stuff"},
        )

    assert result["success"] is True
    mock_mc.assert_awaited_once_with(1, 42, reason="log_added")


async def test_log_work_tool_does_not_trigger_on_create_log_failure():
    """If create_log raises ValueError, maybe_consolidate must not be called."""
    from fabledassistant.services.tools import tasks as tasks_tool

    fake_task = SimpleNamespace(id=42, title="X", status="in_progress")

    with patch(
        "fabledassistant.services.tools.tasks.get_note_by_title",
        new=AsyncMock(return_value=fake_task),
    ), patch(
        "fabledassistant.services.task_logs.create_log",
        new=AsyncMock(side_effect=ValueError("bad input")),
    ), patch(
        "fabledassistant.services.consolidation.maybe_consolidate",
        new=AsyncMock(),
    ) as mock_mc:
        result = await tasks_tool.log_work_tool(
            user_id=1, arguments={"task": "X", "content": "did stuff"},
        )

    assert result["success"] is False
    mock_mc.assert_not_awaited()
