from home_agent.contracts.protocols import EmbeddingProvider, ItemTextRenderer, VectorBackend
from home_agent.contracts.types import (
    RetrievalQuery,
    RetrievedMatch,
    UrgencyLabel,
    VectorQuery,
)


class VectorBackendRetriever:
    def __init__(
        self,
        embedding_provider: EmbeddingProvider,
        item_text_renderer: ItemTextRenderer,
        vector_backend: VectorBackend,
        include_item_kinds: set[str] | None = None,
        prioritize_labels: set[UrgencyLabel] | None = None,
    ) -> None:
        self._embedding_provider: EmbeddingProvider = embedding_provider
        self._item_text_renderer: ItemTextRenderer = item_text_renderer
        self._vector_backend: VectorBackend = vector_backend
        self._include_item_kinds: set[str] | None = include_item_kinds
        self._prioritize_labels: set[UrgencyLabel] = prioritize_labels or set()

    def find_similar(self, query: RetrievalQuery) -> list[RetrievedMatch]:
        rendered = self._item_text_renderer.render(query.item)
        query_vectors = self._embedding_provider.embed_texts([rendered.embedding_text])
        if not query_vectors:
            return []
        results = self._vector_backend.query_similar(
            VectorQuery(
                vector=query_vectors[0],
                top_k=query.top_k,
                min_similarity=query.min_similarity,
                include_item_kinds=self._include_item_kinds,
                prioritize_labels=self._prioritize_labels,
                exclude_keys={(query.item.provider, query.item.external_id)},
            )
        )
        return [
            RetrievedMatch(
                provider=result.provider,
                external_id=result.external_id,
                kind=result.kind,
                summary_text=result.summary_text,
                received_at=result.received_at,
                similarity=result.similarity,
                urgency_label=result.urgency_label,
            )
            for result in results
        ]
