from io import StringIO

from django.core.management import call_command
from django.test import TestCase, override_settings

from core.models import AIRequest, MemoryItem, User, WorkspaceConversation


@override_settings(MEMORY_SEARCH_BACKEND="django")
class MemorySearchCommandTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="memory-search-user",
            email="memory-search@example.com",
            password="pw",
        )
        self.conversation = WorkspaceConversation.objects.create(
            user=self.user,
            platform_type="signal",
            title="Memory Search Scope",
            platform_thread_id="mem-scope-1",
        )
        request = AIRequest.objects.create(
            user=self.user,
            conversation=self.conversation,
            window_spec={},
            operation="memory_propose",
        )
        self.item = MemoryItem.objects.create(
            user=self.user,
            conversation=self.conversation,
            memory_kind="fact",
            status="active",
            content={"text": "Prefers concise updates with action items."},
            source_request=request,
        )

    def test_reindex_command_emits_summary(self):
        out = StringIO()
        call_command(
            "memory_search_reindex",
            user_id=str(self.user.id),
            statuses="active",
            limit=100,
            stdout=out,
        )
        rendered = out.getvalue()
        self.assertIn("memory-search-reindex", rendered)
        self.assertIn("indexed=", rendered)

    def test_query_command_returns_hit(self):
        out = StringIO()
        call_command(
            "memory_search_query",
            user_id=str(self.user.id),
            query="concise updates",
            statuses="active",
            stdout=out,
        )
        rendered = out.getvalue()
        self.assertIn("memory-search-query", rendered)
        self.assertIn(str(self.item.id), rendered)
