from abc import ABC, abstractmethod
from analogai.foundation.infrastructure.storage.neo4j.neo4j_gateway import Neo4jGateway
from analogai.foundation.infrastructure.storage.in_memory.in_memory_storage_adapter_impl import InMemoryStorageAdapterImpl
from analogai.foundation.infrastructure.storage.mongodb.mongodb_storage_adapter_impl import MongoDBStorageAdapterImpl
from analogai.foundation.settings import config


def _cleanup_qdrant() -> None:
    try:
        from analogai.foundation.modules.fact.repositories.infrastructure.qdrant_fact_repository import (
            QdrantFactRepository,
        )
    except Exception:
        return
    try:
        repo = QdrantFactRepository()
    except Exception:
        return
    client = getattr(repo, "_client", None)
    if client is None:
        return
    for collection_name in (
        getattr(repo, "_collection", None),
        getattr(repo, "_links_collection", None),
        getattr(repo, "_turn_index_collection", None),
    ):
        if not collection_name:
            continue
        try:
            client.delete_collection(collection_name=collection_name)
        except Exception:
            continue

class StorageCleaner(ABC):
    @abstractmethod
    def cleanup(self):
        pass

class ProductionEnvironmentStorageCleaner(StorageCleaner):
    def cleanup(self):
        neo4j_gateway = Neo4jGateway()
        with neo4j_gateway.session() as session:
            session.run("MATCH (n) DETACH DELETE n")
        
        storage_adapter = MongoDBStorageAdapterImpl()
        storage_adapter.clear()
        _cleanup_qdrant()

class DevEnvironmentStorageCleaner(StorageCleaner):
    def cleanup(self):
        storage_adapter = InMemoryStorageAdapterImpl()
        storage_adapter.clear()
        _cleanup_qdrant()

def cleanup_storages():
    environment = config.get("ENVIRONMENT")
    cleaner = DevEnvironmentStorageCleaner() if environment in {"development", "testing"} else ProductionEnvironmentStorageCleaner()
    cleaner.cleanup()

if __name__=="__main__":
    cleanup_storages()
