"""Retrieve ContextBase passages in a LlamaIndex query engine."""

from llama_index.core.retrievers import BaseRetriever
from llama_index.core.schema import NodeWithScore, QueryBundle, TextNode

from contextbase import ContextBase


class ContextBaseIndexRetriever(BaseRetriever):
    """Use a server-side index without building a second local vector store."""

    def __init__(
        self,
        client: ContextBase,
        space_id: str,
        *,
        top_k: int = 5,
    ) -> None:
        """Borrow a client whose lifetime is managed by the application."""
        super().__init__()
        self.client = client
        self.space_id = space_id
        self.top_k = top_k

    def _retrieve(self, query_bundle: QueryBundle) -> list[NodeWithScore]:
        """Preserve passage identity and scores in LlamaIndex nodes."""
        space = self.client.spaces.get(self.space_id)
        return [
            NodeWithScore(
                node=TextNode(id_=source.id, text=source.text),
                score=source.score,
            )
            for source in space.search(
                query_bundle.query_str,
                top_k=self.top_k,
            )
        ]
