import logging
from pathlib import Path

from dataiku import Folder

from backends.explorer.factories.db_handler_factory import DbHandlerFactory
from graph.connections.db_handler import DbHandler
from graph.connections.neo4j import Neo4DbHandler
from graph.connections.neo4j.preset import Neo4jPresetConfig
from recipes.build_graph.assets import DATABASE_JSON_FILENAME

logger = logging.getLogger(__name__)


class Neo4jDbHandlerFactory(DbHandlerFactory):
    """
    Factory class for creating database instance objects specifically for the explorer context.
    """

    def __init__(self, db_folder: Folder, snapshot_id: str, neo4j_configuration: Neo4jPresetConfig):
        self.neo4j_configuration = neo4j_configuration
        super().__init__(db_folder, snapshot_id)
    
    def get_db_handler(self) -> DbHandler:
        relative_path_to_db = Path(f"built-graphs/{self.snapshot_id}")
        logger.info(f"Retrieve db from path : {relative_path_to_db}")

        if not self.neo4j_configuration:
            raise ValueError(f"No Neo4j configuration found for webapp")

        try:
            database_json = self.db_folder.read_json(relative_path_to_db / DATABASE_JSON_FILENAME)
            db_name = database_json["params"]["databaseName"]
        except Exception as e:
            logger.error(f"Error reading database.json: {e}")
            raise e

        return Neo4DbHandler(
            uri=self.neo4j_configuration.neo4j_uri,
            username=self.neo4j_configuration.neo4j_username,
            password=self.neo4j_configuration.neo4j_password,
            database=db_name,
        )
