import argparse
import datetime
import torch.distributed as dist
import uuid


def set_version(args: argparse.Namespace) -> argparse.Namespace:
    """ Set the version.

    Args:
        args (argparse.Namespace): The arguments.

    Returns:
        argparse.Namespace: The arguments with the unified version.
    """

    if args.version is None:
        version = None

        # Generate the version.
        if dist.get_rank() == 0:
            version = generate_version()

        # Broadcast the version to all processes.
        version_list = [version]

        dist.broadcast_object_list(
            object_list=version_list,
            src=0,
        )

        # Set the version.
        args.version = version_list[0]

    return args


def generate_version() -> str:
    """ Generate the version.

    Returns:
        str: The version.
    """

    date = datetime.datetime.today().strftime(format='%Y%m%d')
    uid = uuid.uuid4().hex[:8]

    return f'{date}_{uid}'
