from unittest.mock import MagicMock, patch

import pytest

from GramAddict.core.qdrant_memory import QdrantBase
from GramAddict.core.telepathic_engine import TelepathicEngine


@pytest.fixture(autouse=True)
def mock_qdrant():
    with patch("GramAddict.core.qdrant_memory.QdrantClient") as mq:
        yield mq


def test_qdrant_wipe_recreates_collection(mock_qdrant):
    """
    Tests that calling wipe_collection() on QdrantBase successfully calls
    delete_collection AND create_collection to prevent 404 errors.
    """
    mock_client = MagicMock()
    mock_qdrant.return_value = mock_client

    # Missing collection creation during init
    mock_client.collection_exists.return_value = False
    base = QdrantBase("test_collection", vector_size=4)

    assert mock_client.create_collection.call_count == 1

    # Now call wipe_collection
    base.wipe_collection()

    mock_client.delete_collection.assert_called_with("test_collection")
    # create_collection should now have been called a 2nd time
    assert mock_client.create_collection.call_count == 2


def test_telepathic_engine_wipe_uses_wipe_collection(mock_qdrant):
    """
    Tests that TelepathicEngine.wipe() uses the safe wipe_collection method.
    """
    mock_client = MagicMock()
    mock_qdrant.return_value = mock_client

    engine = TelepathicEngine()

    # Spy on the wipe_collection method
    with (
        patch.object(engine.embedding_helper, "wipe_collection") as mock_emb_wipe,
        patch.object(engine.ui_memory, "wipe_collection") as mock_ui_wipe,
    ):
        engine.wipe()

        mock_emb_wipe.assert_called_once()
        mock_ui_wipe.assert_called_once()
