from unittest.mock import AsyncMock, MagicMock, patch

import pytest


@pytest.mark.asyncio
async def test_start_planning_creates_milestone_and_returns_rules():
    # start_planning now creates a MILESTONE (the plan container), not a
    # kind=plan task; its body holds the seeded design template.
    fake_milestone = MagicMock()
    fake_milestone.to_dict.return_value = {"id": 5, "title": "Plan it", "status": "active"}
    applicable = {
        "rules": [{"id": 1, "title": "dev is home", "statement": "...",
                   "topic_title": "git-workflow", "rulebook_title": "FabledSword family"}],
        "truncated": False,
        "subscribed_rulebooks": [{"id": 2, "title": "FabledSword family"}],
    }
    with patch("scribe.services.planning.milestones_svc.create_milestone",
               AsyncMock(return_value=fake_milestone)) as mock_create, \
         patch("scribe.services.planning.rulebooks_svc.get_applicable_rules",
               AsyncMock(return_value=applicable)), \
         patch("scribe.services.planning.notes_svc.list_notes",
               AsyncMock(return_value=([], 3))), \
         patch("scribe.services.planning.projects_svc.get_project",
               AsyncMock(return_value=MagicMock(goal="ship it"))):
        from scribe.services.planning import start_planning
        out = await start_planning(user_id=7, project_id=3, title="Plan it")

    # Created a milestone with the seeded plan-body template.
    kwargs = mock_create.call_args.kwargs
    assert kwargs["project_id"] == 3
    assert kwargs["status"] == "active"
    assert "## Goal" in kwargs["body"]  # seeded template
    # Returned shape
    assert out["milestone"]["id"] == 5
    assert out["applicable_rules"][0]["title"] == "dev is home"
    assert out["subscribed_rulebooks"] == [{"id": 2, "title": "FabledSword family"}]
    assert out["open_task_count"] == 3


@pytest.mark.asyncio
async def test_start_planning_raises_when_project_not_found():
    with patch("scribe.services.planning.projects_svc.get_project",
               AsyncMock(return_value=None)):
        from scribe.services.planning import start_planning
        with pytest.raises(ValueError, match="project 999 not found"):
            await start_planning(user_id=7, project_id=999, title="x")
