import logging
import logging.config
import os

logger = logging.getLogger(__name__)

def logging_setup():
    try:
        from dataiku.customwebapp import get_webapp_config

        webapp_config = get_webapp_config()
        log_level_str = webapp_config.get("log_level", "INFO")
    except Exception:
        log_level_str = "INFO"

    if log_level_str not in ["DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"]:
        logger.error(f"Unexpected log level configuration value {log_level_str}. Using INFO by default.")
        log_level_str = "INFO"

    log_config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {"format": "%(asctime)s - [%(process)d] - %(name)s - %(levelname)s - %(message)s"}
        },
        "handlers": {
            "stdout": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "default"
            }
        },
        "root": {
            "level": log_level_str,
            "handlers": ["stdout"]
        }
    }

    debug_run_folder_path = os.getenv("DEBUG_RUN_FOLDER")
    if debug_run_folder_path:
        local_logs_path = os.path.join(debug_run_folder_path, "logs", "visual-graph.log")
        os.makedirs(os.path.dirname(local_logs_path), exist_ok=True)
        log_config["handlers"]["debug_logfile"] = {
            "class": "logging.FileHandler",
            "filename": local_logs_path,
            "formatter": "default"
        }
        log_config["root"]["handlers"].append("debug_logfile")
    logging.config.dictConfig(log_config)

    logger.info(f"Global log level is {log_level_str}.")
