from pathlib import Path
from pprint import pprint

import yaml


def yaml_config_loader(file_path: str | Path) -> dict:
    """Load a YAML configuration file, with support for the '!include' tag.

    Args:
        file_path (str): Path to the YAML configuration file.

    Returns:
        dict: The configuration dictionary.
    """

    # Define a custom constructor for handling the '!include' tag
    def include_constructor(loader, node):
        # Get the path from the node value
        file_name = loader.construct_scalar(node)
        # Assuming the file path is relative to the current file
        with open(file_name) as inputfile:
            return yaml.safe_load(inputfile)

    # Add the custom constructor to the yaml loader
    yaml.SafeLoader.add_constructor("!include", include_constructor)

    with open(file_path) as file:
        config = yaml.load(file, Loader=yaml.SafeLoader)

    return config


def save_yaml_config(config: dict, file_path: str) -> None:
    """Save a dictionary to a YAML file.

    Args:
        config (dict): The configuration dictionary to save.
        file_path (str): The path to save the configuration file.
    """
    with open(file_path, "w") as file:
        yaml.dump(config, file)


if __name__ == "__main__":
    # Usage example
    config = yaml_config_loader("configs/config.yaml")
    save_yaml_config(config, "configs/generated_config.yaml")
    pprint(config)
