"""End-to-end integration test with embedded Kùzu + LanceDB.

No Docker required — uses embedded Kùzu and LanceDB in tmp_path.

Run with:
    uv run pytest tests/integration/test_local_mode.py -v
"""

import pytest

from tracemem_core.config import TraceMemConfig
from tracemem_core.messages import Message, ToolCall
from tracemem_core.storage.graph.kuzu_store import KuzuGraphStore
from tracemem_core.tracemem import TraceMem

from ..conftest import MockEmbedder


@pytest.fixture
def mock_embedder():
    return MockEmbedder()


class TestLocalModeIntegration:
    """End-to-end tests with embedded stores."""

    async def test_creates_kuzu_store(self, tmp_path, mock_embedder):
        """Verify default config uses KuzuGraphStore."""
        config = TraceMemConfig(
                        home=tmp_path / ".tracemem",
        )
        tm = TraceMem(config=config, embedder=mock_embedder)
        assert isinstance(tm._graph_store, KuzuGraphStore)

    async def test_local_mode_import_and_search(self, tmp_path, mock_embedder):
        """Test full import + search cycle in local mode."""
        config = TraceMemConfig(
                        home=tmp_path / ".tracemem",
        )
        async with TraceMem(config=config, embedder=mock_embedder) as tm:
            messages = [
                Message(role="user", content="Read the auth.py file"),
                Message(
                    role="assistant",
                    content="I'll read that file for you",
                    tool_calls=[
                        ToolCall(
                            id="call_1",
                            name="read_file",
                            args={"file_path": str(tmp_path / "auth.py")},
                        )
                    ],
                ),
                Message(
                    role="tool",
                    content="def authenticate(): pass",
                    tool_call_id="call_1",
                ),
            ]
            result = await tm.import_trace("conv-1", messages)

            assert "user_text" in result
            assert "agent_text" in result

    async def test_local_mode_storage_paths_created(self, tmp_path, mock_embedder):
        """Verify that storage directories are created."""
        home = tmp_path / ".tracemem"
        config = TraceMemConfig(
                        home=home,
        )
        async with TraceMem(config=config, embedder=mock_embedder) as tm:
            pass

        # Graph directory should exist (Kùzu creates it)
        assert (home / "graph").exists()
        # Vectors directory should exist (LanceDB creates it)
        assert (home / "vectors").exists()

    async def test_local_mode_get_context(self, tmp_path, mock_embedder):
        """Test context retrieval in local mode."""
        config = TraceMemConfig(
                        home=tmp_path / ".tracemem",
        )
        async with TraceMem(config=config, embedder=mock_embedder) as tm:
            messages = [
                Message(role="user", content="Hello world"),
                Message(role="assistant", content="Hi there!"),
            ]
            result = await tm.import_trace("conv-1", messages)

            ctx = await tm.get_context(result["user_text"])
            assert ctx.user_text is not None
            assert ctx.user_text.text == "Hello world"
            assert ctx.agent_text is not None
            assert ctx.agent_text.text == "Hi there!"

    async def test_local_mode_trajectory(self, tmp_path, mock_embedder):
        """Test trajectory traversal in local mode."""
        config = TraceMemConfig(
                        home=tmp_path / ".tracemem",
        )
        async with TraceMem(config=config, embedder=mock_embedder) as tm:
            messages = [
                Message(role="user", content="Step 1"),
                Message(role="assistant", content="Response 1"),
            ]
            result = await tm.import_trace("conv-1", messages)

            traj = await tm.get_trajectory(result["user_text"])
            assert len(traj.steps) >= 2

    async def test_neo4j_mode_creates_neo4j_store(self, tmp_path, mock_embedder):
        """Verify that graph_store='neo4j' creates Neo4jGraphStore."""
        config = TraceMemConfig(
                        home=tmp_path / ".tracemem",
            graph_store="neo4j",
        )
        tm = TraceMem(config=config, embedder=mock_embedder)

        # Import lazily to avoid requiring neo4j package at module level
        from tracemem_core.storage.graph.neo import Neo4jGraphStore

        assert isinstance(tm._graph_store, Neo4jGraphStore)
