from __future__ import annotations

import os

from pydantic import SecretStr

from backends.explorer.utils.webapp_config import webapp_config
from backends.utils import strtobool
from graph.connections.neo4j.preset import Neo4jPresetConfig


def get_neo4j_preset_from_webapp() -> Neo4jPresetConfig | None:
    """
    Retrieves the Neo4j configuration directly from the webapp settings.

    Returns:
        A Neo4jPresetConfig object if the configuration is found, otherwise None.
    """
    neo4j_config = webapp_config.neo4j_configuration
    
    if not neo4j_config:
        return None

    return Neo4jPresetConfig.from_dict(neo4j_config)

def get_neo4j_preset_from_env() -> Neo4jPresetConfig | None:
    """
    Retrieves the Neo4j configuration from environment variables.

    Returns:
        A Neo4jPresetConfig object if all required environment variables are set, otherwise None.
    """
    neo4j_uri = os.getenv("NEO4J_URI")
    neo4j_username = os.getenv("NEO4J_USERNAME")
    neo4j_password = os.getenv("NEO4J_PASSWORD")
    if (neo4j_uri and neo4j_username and neo4j_password):
        return Neo4jPresetConfig(
            neo4j_uri=neo4j_uri,
            neo4j_username=neo4j_username,
            neo4j_password=SecretStr(neo4j_password))
    return None
    

def get_webapp_neo4j_preset() -> Neo4jPresetConfig | None:
    """
    Retrieves the Neo4j preset configured in the webapp settings, including its configuration details.
    
    Returns:
        A Neo4jPresetConfig object if a preset is configured and found, otherwise None.
    """
    use_remote_webapp_settings = strtobool(os.getenv("USE_REMOTE_WEBAPP_SETTINGS", "False"))

    if use_remote_webapp_settings:
        preset = get_neo4j_preset_from_env()
    else:
        preset = get_neo4j_preset_from_webapp()

    if not preset:
        return None

    return preset
