import pytest
from unittest.mock import AsyncMock, MagicMock
from neo_cortex.models import MemoryRecord


@pytest.fixture
def mock_cortex():
    """Mock cortex with spontaneous() returning test memories."""
    cortex = AsyncMock()
    cortex.spontaneous.return_value = [
        MemoryRecord(
            id="sp1", session_id="s1", project="test-project",
            topic="TDD", question="what is TDD?",
            answer_preview="Test driven development",
            document="TDD is a methodology...",
        ),
        MemoryRecord(
            id="sp2", session_id="s2", project="general",
            topic="memory", question="how does memory work?",
            answer_preview="Memory uses embeddings",
            document="Memory system stores embeddings...",
        ),
    ]
    cortex.index = MagicMock()
    cortex.index.get_structured.return_value = None
    return cortex


@pytest.fixture
def mock_cortex_empty():
    """Mock cortex with spontaneous() returning empty."""
    cortex = AsyncMock()
    cortex.spontaneous.return_value = []
    return cortex


def test_spontaneous_tool_exists():
    """memory_spontaneous MCP tool is registered."""
    from neo_cortex.mcp import memory_spontaneous
    assert memory_spontaneous is not None
    assert memory_spontaneous.name == "memory_spontaneous"


@pytest.mark.asyncio
async def test_spontaneous_returns_mbel_format(mock_cortex):
    """Spontaneous compact output contains MBEL-formatted references."""
    from neo_cortex import mcp as mcp_module
    original = mcp_module._cortex
    try:
        mcp_module._cortex = mock_cortex
        result = await mcp_module.memory_spontaneous.fn(n=2, detail="compact")
        assert isinstance(result, str)
        assert "sp1" in result
        assert "sp2" in result
    finally:
        mcp_module._cortex = original


@pytest.mark.asyncio
async def test_spontaneous_returns_dict_on_empty(mock_cortex_empty):
    """Spontaneous returns status dict when no memories qualify."""
    from neo_cortex import mcp as mcp_module
    original = mcp_module._cortex
    try:
        mcp_module._cortex = mock_cortex_empty
        result = await mcp_module.memory_spontaneous.fn(n=3)
        assert isinstance(result, dict)
        assert result["count"] == 0
    finally:
        mcp_module._cortex = original


@pytest.mark.asyncio
async def test_spontaneous_full_returns_json(mock_cortex):
    """Spontaneous detail=full returns raw JSON with model_dump."""
    from neo_cortex import mcp as mcp_module
    original = mcp_module._cortex
    try:
        mcp_module._cortex = mock_cortex
        result = await mcp_module.memory_spontaneous.fn(n=2, detail="full")
        assert isinstance(result, dict)
        assert result["count"] == 2
        assert len(result["memories"]) == 2
    finally:
        mcp_module._cortex = original
