#!/usr/bin/python3
import os, sys
import yaml
import errno
import argparse
import logging
import pprint
from ldmsd.parser_util import *

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='LDMS Monitoring YAML Cluster Configuration Parser')
    required = parser.add_argument_group('required arguments')
    required.add_argument('-y','--ldms_config', metavar='LDMSD_YAML_FILE', required=True,
                        help='Path to LDMSD YAML configuration file. ')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-p','--output_path', "--generate_config_path", metavar="OUTPUT_DIR_NAME", required=False,
                        help='Path to directory to store generated v4 configuration files for an entire LDMS cluster. '
                             'Samplers with identical configurations share a single configuration file. ',
                        default=False)
    group.add_argument('-n','--daemon_name', metavar='DAEMON_NAME', required=False,
                        default=False,
                        help='Daemon name to generate configuration from YAML file')
    parser.add_argument('-L','--log_file', metavar='LOG_FILE_NAME', default=None,
                        help='log file (default is stderr)')
    parser.add_argument('-l','--log_level', metavar="LOG_LEVEL", default="ERROR",
                        help='set logging level to one of DEBUG,INFO,WARNING,ERROR,CRITICAL')
    args = parser.parse_args()
    level = args.log_level.upper()
    if not isinstance(logging.getLevelName(level), int):
        logging.critical(f"Requested log level is undefined: {level}")
        sys.exit(errno.EINVAL)
    if not args.log_file is None:
        logging.basicConfig(filename=args.log_file, level=level)
    else:
        logging.basicConfig(level=level)

    config_fp = open(args.ldms_config)
    conf_spec = yaml.safe_load(config_fp)

    logging.debug("ORIGINAL YAML after anchor expansion")
    logging.debug(pprint.pformat(conf_spec))

    if not isinstance(conf_spec, (list, dict)):
        logging.error(f"Input {args.ldms_config} is not yaml. Contents:")
        logging.error(conf_spec)
        sys.exit(errno.EINVAL)

    cluster = YamlCfg(None, None, conf_spec, args)

    if args.daemon_name:
        ldmsd_cfg_str = cluster.daemon_config(args.ldms_config, args.daemon_name)
        import json
        logging.debug("# YamlCfg after processing:")
        logging.debug(cluster)
        logging.debug("# ========================================================")
        print(f"# {__file__} generated {args.daemon_name} from {args.ldms_config} to stdout")
        print(f'{ldmsd_cfg_str}')
        sys.exit(0)

    if args.output_path:
        logging.debug(f"{__file__} wrote group configs from {args.ldms_config} to {args.output_path}")
        logging.debug("# --------------------------------------------------------")
        rc = cluster.config_v4(args.output_path)
        logging.debug("YamlCfg after processing:")
        logging.debug(cluster)
        logging.debug("# ========================================================")
        if rc:
            sys.exit(rc)
        logging.info('LDMSD config files generated')
        sys.exit(0)

    if not args.output_path and not args.ldms_config and not args.daemon_name:
        logging.warning('No action detected. Exiting.')

    sys.exit(0)
