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

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

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 if level else "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"]
# Kafka Configuration Variables
KAFKA_HOST = config["KAFKA"]["kafka_host"]
KAFKA_PORT = config["KAFKA"]["kafka_port"]
KAFKA_TOPIC = config["KAFKA"]["kafka_topic"]

# Read the configuration file

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

MODEL = _config["model"]
PARAMETER_INFO = _config["parameter"]
PARAMETER_INPUT = MODEL["model_input_features"]
OUTPUT_DATA = _config["output"]
OUTPUT_PARAMETER_QUICK_MAP_INFO = OUTPUT_DATA["quick_map"]
TARGET_VALUE = OUTPUT_DATA["target"]
OUTPUT_SITE_ID = OUTPUT_DATA["site"]
