#!/usr/bin/env python3
"""Set the domain from a json file containing definitions."""
import argparse
import sys
import json
import os
import logging
import surfex


def parse(argv):
    """Parse the command line input arguments."""
    parser = argparse.ArgumentParser()

    parser.add_argument('--version', action='version',
                        version=f'surfex {surfex.__version__}')
    parser.add_argument('--domain', '-d', required=True, type=str, help="Name of domain")
    parser.add_argument('--domains', required=True, type=str, help="Domain definitions")
    parser.add_argument('--harmonie', action="store_true", help="Domain in harmonie definition")
    parser.add_argument('--indent', required=False, default=2, type=int, help="Indented output")
    parser.add_argument('--output', '-o', required=True, nargs='?')
    parser.add_argument('--debug', help="Show debug information", action="store_true")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    return parser.parse_args(argv)


if __name__ == "__main__":

    try:
        args = parse(sys.argv[1:])
        debug = args.debug

        if debug:
            logging.basicConfig(
                format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)s %(message)s',
                level=logging.DEBUG)
        else:
            logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
        logging.info("************ set_domain ******************")
        domain = args.domain
        domains = args.domains
        output = args.output
        indent = args.indent
        harmonie_mode = args.harmonie
        if os.path.exists(domains):
            with open(domains, mode="r", encoding="utf-8") as file_handler:
                domains = json.load(file_handler)
            domain_json = surfex.set_domain(domains, domain, hm_mode=harmonie_mode)
            if domain_json is not None:
                with open(output, mode="w", encoding="utf-8") as file_handler:
                    json.dump(domain_json, file_handler, indent=indent)
            else:
                raise Exception
        else:
            raise FileNotFoundError
    except Exception as ex:
        raise f"Could not set domain: {str(ex)}"
