"""Build a vector store from configuration.

The in-memory backend is a process-wide singleton so that ingestion and
retrieval (which open separate sessions) share the same vectors.
"""

from __future__ import annotations

from legate.config import Settings, get_settings
from legate.rag.vectorstore.base import VectorStore
from legate.rag.vectorstore.memory import InMemoryVectorStore

_memory_store: InMemoryVectorStore | None = None


def _get_memory_store() -> InMemoryVectorStore:
    global _memory_store
    if _memory_store is None:
        _memory_store = InMemoryVectorStore()
    return _memory_store


def reset_memory_store() -> None:
    """Clear the in-memory store (used between tests)."""
    if _memory_store is not None:
        _memory_store.reset()


def build_vector_store(settings: Settings | None = None) -> VectorStore:
    settings = settings or get_settings()
    backend = (settings.vector_store_backend or "qdrant").lower()

    if backend == "memory":
        return _get_memory_store()
    if backend == "qdrant":
        from legate.rag.vectorstore.qdrant import QdrantVectorStore

        return QdrantVectorStore(url=settings.qdrant_url)

    raise ValueError(f"unsupported vector store backend '{backend}'; available: qdrant, memory")
