"""Chroma vector adapter (Phase 6)."""
from __future__ import annotations

from typing import Iterable, List

from ..types import VectorMetadata


class ChromaAdapter:
    """Minimal Chroma adapter.

    Requires chromadb package.
    """

    def __init__(self, path: str):
        try:
            import chromadb
        except Exception as exc:
            raise RuntimeError("chromadb not installed") from exc
        try:
            import onnxruntime  # noqa: F401
        except Exception as exc:
            raise RuntimeError("onnxruntime not installed for chroma embeddings") from exc

        self.client = chromadb.PersistentClient(path=path)
        self.collection = self.client.get_or_create_collection("databridge_kb")

    def add_metadata(self, items: Iterable[VectorMetadata]) -> int:
        ids = []
        metadatas = []
        documents = []
        for item in items:
            ids.append(item.id)
            meta = item.model_dump()
            # Chroma metadata must be flat scalars
            for k, v in list(meta.items()):
                if isinstance(v, list):
                    meta[k] = ", ".join(str(x) for x in v)
                elif isinstance(v, dict):
                    import json
                    meta[k] = json.dumps(v)
            metadatas.append(meta)
            documents.append(item.id)
        if ids:
            self.collection.add(ids=ids, metadatas=metadatas, documents=documents)
        return len(ids)

    def search(self, query: str, top_k: int = 5) -> List[VectorMetadata]:
        res = self.collection.query(query_texts=[query], n_results=top_k)
        items = []
        for meta in (res.get("metadatas") or [[]])[0]:
            items.append(VectorMetadata(**meta))
        return items
