from dotenv import load_dotenv
import os
import sys
from configparser import ConfigParser, BasicInterpolation
import yaml

# Configuration File Constants
_application_conf = "./conf/application.conf"
_default_conf = "./config.env"
data_conf = "./conf/data.yml"

load_dotenv(dotenv_path=_default_conf)


class EnvInterpolation(BasicInterpolation):
    """
    Interpolation which expands environment variables in values.
    """

    def before_get(self, parser, section, option, value, defaults):
        value = super().before_get(parser, section, option, value, defaults)

        if not os.path.expandvars(value).startswith("$"):
            return os.path.expandvars(value)
        else:
            return


try:
    config = ConfigParser(interpolation=EnvInterpolation())
    config.read(_application_conf)
except Exception as e:
    print(f"Error while loading the config: {e}")
    print("Failed to Load Configuration. Exiting!!!")
    sys.exit()


class Logging:
    level = config.get("LOGGING", "level", fallback="INFO")
    level = level or "INFO"
    tb_flag = config.getboolean("LOGGING", "traceback", fallback=True)
    tb_flag = tb_flag if tb_flag is not None else True


# Configuration Variables
# Kairos Configuration Variables
KAIROS_DB_HOST = config["KAIROS_DB"]["uri"]
# Postgres Configuration Variables
POSTGRES_URI = config["POSTGRES"]["postgres_uri"]

# Read the configuration file

with open(data_conf, "r") as _cf:
    _config = yaml.full_load(_cf)

METADATA = _config["metadata"]
