import logging
import time
import sys
import torch
import torchvision
import os


def log_args(title, args, logger):
    """Log arguments in a formatted way."""
    logger.info(f"------------------------ {title} ------------------------")
    str_list = []
    for arg in vars(args):
        dots = "." * (48 - len(arg))
        str_list.append("  {} {} {}".format(arg, dots, getattr(args, arg)))
    for arg in sorted(str_list, key=lambda x: x.lower()):
        logger.info(arg)
    logger.info(f"--------------------- end of {title} ---------------------")


def set_logger(args, name=""):
    """Set up logging configuration."""
    logger = logging.getLogger("evo_result")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "%(asctime)s - %(levelname)s: - %(message)s", datefmt="%m-%d %H:%M"
    )
    args.output_dir = os.path.join(
        args.output_dir, time.strftime(f"%m_%d_%H_%M_%S", time.localtime())
    )
    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)

    fh = logging.FileHandler(f"{args.output_dir}/info.log")
    fh.setLevel(logging.INFO)
    fh.setFormatter(formatter)

    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)

    logger.info("PyThon  version : {}".format(sys.version.replace("\n", " ")))
    logger.info("PyTorch version : {}".format(torch.__version__))
    logger.info("cuDNN   version : {}".format(torch.backends.cudnn.version()))
    logger.info("Vision  version : {}".format(torchvision.__version__))
    log_args("arg_list", args, logger)

    return logger
