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

import os
from logging import WARNING
from pathlib import Path

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

from repo.conf import base_schema
from repo.conf.base_schema import BaseConfig

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 repo_SAVE_PATH is not set.

    """
    # Resolve the configuration
    OmegaConf.resolve(cfg)
    # Get the environmental variable for the dump folder
    repo_save_path = os.environ.get("repo_SAVE_PATH", "")
    # Raise an error if the environmental variable is not set
    if not repo_save_path:
        msg = "The environmental variable repo_SAVE_PATH is not set."
        raise ValueError(msg)
    # Dump the configuration to a YAML file under the dump folder
    Path(repo_save_path).mkdir(parents=True, exist_ok=True)
    if (Path(repo_save_path) / "config.yaml").exists():
        log(WARNING, "The config.yaml file already exists. It will be overwritten.")
        (Path(repo_save_path) / "config.yaml").unlink()
    OmegaConf.save(cfg, repo_save_path + "/config.yaml")


if __name__ == "__main__":
    main()
