from unittest.mock import AsyncMock, patch

import pytest
from tests.helpers import fake_task


pytestmark = pytest.mark.usefixtures("_bind_user")


@pytest.mark.asyncio
async def test_start_planning_tool_delegates_to_service():
    payload = {"milestone": {"id": 5}, "applicable_rules": [], "subscribed_rulebooks": [],
               "applicable_rules_truncated": False, "project_goal": "", "open_task_count": 0}
    with patch("scribe.mcp.tools.tasks.planning_svc.start_planning",
               AsyncMock(return_value=payload)) as mock:
        from scribe.mcp.tools.tasks import start_planning
        out = await start_planning(project_id=3, title="Plan it")
    assert out["milestone"]["id"] == 5
    assert mock.call_args.kwargs == {"user_id": 7, "project_id": 3, "title": "Plan it"}


@pytest.mark.asyncio
async def test_get_task_augments_plan_with_rules():
    applicable = {"rules": [{"id": 1, "title": "r"}], "truncated": False,
                  "subscribed_rulebooks": [{"id": 2, "title": "rb"}]}
    with patch("scribe.mcp.tools.tasks.notes_svc.get_note_for_user",
               AsyncMock(return_value=(fake_task(task_kind="plan", id=9, project_id=3), "owner"))), \
         patch("scribe.mcp.tools.tasks.rulebooks_svc.get_applicable_rules",
               AsyncMock(return_value=applicable)):
        from scribe.mcp.tools.tasks import get_task
        out = await get_task(task_id=9)
    assert out["applicable_rules"] == [{"id": 1, "title": "r"}]
    assert out["subscribed_rulebooks"] == [{"id": 2, "title": "rb"}]
    assert out["applicable_rules_truncated"] is False


@pytest.mark.asyncio
async def test_get_task_work_kind_has_no_rules():
    with patch("scribe.mcp.tools.tasks.notes_svc.get_note_for_user",
               AsyncMock(return_value=(fake_task(task_kind="work", id=9, project_id=3), "owner"))), \
         patch("scribe.mcp.tools.tasks.rulebooks_svc.get_applicable_rules",
               AsyncMock()) as mock_rules:
        from scribe.mcp.tools.tasks import get_task
        out = await get_task(task_id=9)
    assert "applicable_rules" not in out
    assert not mock_rules.called
