"""Script for resolving the hydra configuration."""

import os
from logging import DEBUG, WARNING
from pathlib import Path

import hydra
from flwr.common import log
from omegaconf import OmegaConf

from mt_dao.conf import base_schema
from mt_dao.conf.base_schema import BaseConfig
from mt_dao.constants import CONFIG_FILE_YAML, mt_dao_SAVE_PATH

base_schema.register_config(name="base_schema")


# Define strategy
@hydra.main(config_path="conf/", config_name="base", version_base=None)
def main(cfg: BaseConfig) -> None:
    """Resolve the configuration and dump it to a YAML file.

    Parameters
    ----------
    cfg : BaseConfig
        The configuration object.

    Raises
    ------
    ValueError
        If the environmental variable mt_dao_SAVE_PATH is not set.

    """
    # Resolve the configuration
    OmegaConf.resolve(cfg)
    # Get the environmental variable for the dump folder
    mt_dao_save_path = os.environ.get(mt_dao_SAVE_PATH, "")
    # Raise an error if the environmental variable is not set
    if not mt_dao_save_path:
        msg = "The environmental variable mt_dao_SAVE_PATH is not set."
        raise ValueError(msg)
    # Dump the configuration to a YAML file under the dump folder
    Path(mt_dao_save_path).mkdir(parents=True, exist_ok=True)
    if (Path(mt_dao_save_path) / CONFIG_FILE_YAML).exists():
        log(WARNING, "The config.yaml file already exists. It will be overwritten.")
        (Path(mt_dao_save_path) / CONFIG_FILE_YAML).unlink()
    OmegaConf.save(cfg, mt_dao_save_path + f"/{CONFIG_FILE_YAML}")
    log(
        DEBUG,
        "Configuration successfully elaborated and dumped to %s",
        mt_dao_save_path + f"/{CONFIG_FILE_YAML}",
    )


if __name__ == "__main__":
    main()
