"""Adapter for synchronous ChromaDB clients (e.g., in-memory for testing)."""

from __future__ import annotations

from typing import Any, Sequence


class SyncCollectionWrapper:
    """Wrapper that adds async interface to sync ChromaDB collections."""

    def __init__(self, sync_collection: Any):
        """Initialize wrapper.

        Parameters
        ----------
        sync_collection:
            Synchronous ChromaDB collection.
        """
        self._collection = sync_collection

    async def query(self, **kwargs) -> Any:
        """Async wrapper for sync query method."""
        return self._collection.query(**kwargs)

    async def get(self, **kwargs) -> Any:
        """Async wrapper for sync get method."""
        return self._collection.get(**kwargs)

    async def count(self) -> int:
        """Async wrapper for sync count method."""
        return self._collection.count()


class SyncClientAdapter:
    """Adapter for synchronous ChromaDB clients.

    This adapter wraps a synchronous in-memory ChromaDB client to provide
    the async interface required by ChromaSQL's multi-collection system.

    Parameters
    ----------
    client:
        Synchronous ChromaDB client.
    collection_names:
        List of collection names available for querying.
    """

    def __init__(self, client: Any, collection_names: Sequence[str]):
        """Initialize the adapter.

        Parameters
        ----------
        client:
            Synchronous ChromaDB client (e.g., chromadb.Client()).
        collection_names:
            List of collection names.
        """
        self.client = client
        self.collection_names = list(collection_names)
        self._collection_cache: dict[str, SyncCollectionWrapper] = {}

    async def get_collection(self, name: str) -> SyncCollectionWrapper:
        """Get a collection by name, with caching.

        Parameters
        ----------
        name:
            Collection name.

        Returns
        -------
        Wrapped sync collection with async interface.
        """
        if name in self._collection_cache:
            return self._collection_cache[name]

        sync_collection = self.client.get_collection(name=name)
        wrapped = SyncCollectionWrapper(sync_collection)
        self._collection_cache[name] = wrapped
        return wrapped

    async def list_collection_names(self) -> Sequence[str]:
        """List all available collection names.

        Returns
        -------
        Sequence[str]
            Collection names provided at initialization.
        """
        return self.collection_names
