from typing import List, Dict, Any, Optional
from analogai.foundation.infrastructure.storage.query_storage_adapter import QueryStorageAdapter, QueryBuilder
from analogai.foundation.infrastructure.storage.mongodb.mongodb_storage_adapter_impl import MongoDBStorageAdapterImpl
from analogai.foundation.common.logging.app_logger import app_logger
from typeguard import typechecked

class MongoDBQueryStorageAdapterImpl(QueryStorageAdapter):
    
    def __init__(self):
        self.mongodb_adapter = MongoDBStorageAdapterImpl()

    @typechecked
    def store(self, collection: str, data: Any) -> None:
        if hasattr(data, '__dict__'):
            document = data.__dict__.copy()
        else:
            document = dict(data)
        self.mongodb_adapter.store(collection, document)

    @typechecked
    def retrieve_by_id(self, collection: str, id: str) -> Optional[Any]:
        return self.mongodb_adapter.retrieve_by_id(collection, id)

    @typechecked
    def retrieve_by_attributes(self, collection: str, query: Dict[str, Any]) -> List[Any]:
        return self.mongodb_adapter.retrieve_by_attributes(collection, query)

    @typechecked
    def delete(self, collection: str, id: str) -> bool:
        try:
            self.mongodb_adapter.delete(collection, id)
            return True
        except ValueError:
            return False

    @typechecked
    def clear(self, collection: str) -> None:
        self.mongodb_adapter.db[collection].delete_many({})

    @typechecked
    def query(self, collection: str, query_dict: Dict[str, Any]) -> QueryBuilder:
        app_logger.debug(f"Starting MongoDB query builder for {collection}: {query_dict}")
        return QueryBuilder(self, collection, query_dict)

    @typechecked
    def count(self, collection: str, query_dict: Optional[Dict[str, Any]] = None) -> int:
        if query_dict is None:
            query_dict = {}
        return self.mongodb_adapter.db[collection].count_documents(query_dict)
