#!python
import os
import sys
import argparse
import logging
import logging.handlers
from atomic_hpc.config_yaml import format_config_yaml
from atomic_hpc.deploy_runs import deploy_runs


def run(fpath, basepath="", log_level='INFO', ignore_fail=False, overwrite=False):
    """

    Parameters
    ----------
    fpath: str
    basepath: str
    log_level: str
    ignore_fail: bool
        if True; if a command line execution fails continue the run
    overwrite: bool
        if True; if a run's output directory already exists, then remove it

    Returns
    -------

    """

    root = logging.getLogger()
    root.handlers = []  # remove any existing handlers
    root.setLevel(logging.DEBUG)
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setLevel(getattr(logging, log_level.upper()))
    # TODO align messages
    formatter = logging.Formatter('%(levelname)8s: %(module)10s: %(message)s')
    stream_handler.setFormatter(formatter)
    stream_handler.propogate = False
    stream_handler.addFilter(logging.Filter('atomic_hpc'))
    root.addHandler(stream_handler)

    # TODO add option for file logger
    # file_handler = logging.FileHandler(os.path.join(outdir, ipynb_name + '.config.log'), 'w')
    # file_handler.setLevel(getattr(logging, log_level.upper()))
    # file_handler.setFormatter(formatter)
    # file_handler.propogate = False
    # file_handler.addFilter(logging.Filter('atomic_hpc'))
    # root.addHandler(file_handler)

    fpath = os.path.abspath(fpath)
    basepath = os.path.abspath(basepath)

    runs = format_config_yaml(fpath)
    exists_error = not overwrite
    exec_errors = not ignore_fail
    deploy_runs(runs, basepath, exists_error=exists_error, exec_errors=exec_errors)


class ErrorParser(argparse.ArgumentParser):
    """
    on error; print help string
    """
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

if __name__ == "__main__":

    parser = ErrorParser(
        description='use a config.yaml file to run process on a local or remote host'
    )
    parser.add_argument("configpath", type=str,
                        help='yaml config file path', metavar='filepath')
    parser.add_argument("-b", "--basepath", type=str, metavar='str',
                        help='path to use when resolving relative paths in the config file',
                        default=os.getcwd())
    parser.add_argument("-ow", "--overwrite", action="store_true",
                        help="if a run's output directory already exists, then remove it (default is to abort the run)")
    parser.add_argument("-if", "--ignore-fail", action="store_true",
                        help='if a command line execution fails continue the run (default is to abort the run)')
    parser.add_argument("-log", "--log-level", type=str, default='info',
                        choices=['debug', 'info', 'warning', 'error'],
                        help='the logging level to output to screen/file')

    args = parser.parse_args()
    options = vars(args)
    filepath = options.pop('configpath')
    run(filepath, **options)
