import json
import locale
import os

from datetime import datetime
from logging.config import dictConfig
from pathlib import Path

from traces_explorer.backend.utils.dataiku_api import dataiku_api


year, date = datetime.now().strftime("%Y"), datetime.now().strftime("%Y-%m-%d")

# This is the default config that will be used if no local config is found
# PLEASE DO NOT UPDATE, check README.md for more information
DEFAULT_CONFIG = {
    "webapp_config": {},
    "default_project_key": "DEFAULT_PROJECT"
}


def update(original, updates):
    # Update the default config with local config
    for key, value in updates.items():
        if isinstance(original.get(key), list) and isinstance(value, list):
            original[key] = value
        elif isinstance(original.get(key), dict) and isinstance(value, dict):
            original[key].update(value)
        else:
            original[key] = value
    return original


def load_config():
    local_config_path = Path(__file__).parent / "local_config.json"
    config = DEFAULT_CONFIG.copy()
    # Override with local configuration if it exists
    if local_config_path.exists():
        with open(local_config_path, 'r', encoding=locale.getpreferredencoding(False)) as local_config_file:
            local_config = json.load(local_config_file)
            # Update the default config with local config
            update(config, local_config)
    else:
        print("No local configuration found. Default configuration will be used. Create a local_config.json file to override it.")
    return config


CONFIG = load_config()
os.environ["DKU_CURRENT_PROJECT_KEY"] = CONFIG.get("default_project_key", "")
os.environ["DKU_CUSTOM_WEBAPP_CONFIG"] = json.dumps(
    CONFIG.get("webapp_config"), ensure_ascii=False)


def get_setup_for_dataiku_client():
    return {
        "webapp_config": CONFIG.get("webapp_config"),
        "default_project_key": CONFIG.get("default_project_key"),
    }


dictConfig(
    {
        "version": 1,
        "formatters": {
            "default": {
                "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
            }
        },
        "handlers": {
            "wsgi": {
                "class": "logging.StreamHandler",
                "stream": "ext://flask.logging.wsgi_errors_stream",
                "formatter": "default",
            }
        },
        "root": {"level": "INFO", "handlers": ["wsgi"]},
    }
)


def setup_dataiku_client():
    dataiku_setup = get_setup_for_dataiku_client()
    dataiku_api.setup(**dataiku_setup)
