"""Qdrant VectorStore implementation."""
from __future__ import annotations

from typing import Any

from .base import VectorStore


class QdrantVectorStore(VectorStore):
    """VectorStore backed by Qdrant.

    Requires: pip install trustmem[qdrant]
    """

    def __init__(
        self,
        url: str = "http://localhost:6333",
        collection_name: str = "trustmem",
        vector_size: int = 1536,
        api_key: str | None = None,
    ) -> None:
        try:
            from qdrant_client import QdrantClient
            from qdrant_client.models import Distance, VectorParams
        except ImportError:
            raise ImportError(
                "qdrant-client is required. Install with: pip install trustmem[qdrant]"
            )

        self._client = QdrantClient(url=url, api_key=api_key)
        self._collection = collection_name
        self._vector_size = vector_size

        # Create collection if it doesn't exist
        collections = [c.name for c in self._client.get_collections().collections]
        if collection_name not in collections:
            self._client.create_collection(
                collection_name=collection_name,
                vectors_config=VectorParams(
                    size=vector_size,
                    distance=Distance.COSINE,
                ),
            )

    def upsert(self, id: str, vector: list[float], payload: dict) -> None:
        from qdrant_client.models import PointStruct

        self._client.upsert(
            collection_name=self._collection,
            points=[PointStruct(id=id, vector=vector, payload=payload)],
        )

    def search(
        self,
        query_vector: list[float],
        limit: int = 10,
        filters: dict[str, Any] | None = None,
    ) -> list[dict]:
        from qdrant_client.models import (
            FieldCondition, Filter, MatchValue, Range,
        )

        conditions = []
        if filters:
            filters = dict(filters)  # don't mutate caller's dict
            filters.pop("min_zone", None)  # legacy: ignored
            for k, v in filters.items():
                conditions.append(
                    FieldCondition(key=k, match=MatchValue(value=v))
                )
        query_filter = Filter(must=conditions) if conditions else None

        results = self._client.search(
            collection_name=self._collection,
            query_vector=query_vector,
            limit=limit,
            query_filter=query_filter,
        )
        return [
            {"id": str(r.id), "score": r.score, "payload": r.payload or {}}
            for r in results
        ]

    def delete(self, id: str) -> None:
        from qdrant_client.models import PointIdsList

        self._client.delete(
            collection_name=self._collection,
            points_selector=PointIdsList(points=[id]),
        )

    def update_payload(self, id: str, payload: dict) -> None:
        self._client.set_payload(
            collection_name=self._collection,
            payload=payload,
            points=[id],
        )

    def count(self) -> int:
        info = self._client.get_collection(self._collection)
        return info.points_count
