"""
eMews CORE network emulator service generator tool.
This tool supports CORE 9 and is compatible with CORE 8 for legacy purposes.
"""
import argparse
import pathlib

from ruamel.yaml import YAML

from emews.base.config import get_root_path

HELP_TXT = "CORE service generator - generates a CORE service interfacing the given eMews service by name"

parser = argparse.ArgumentParser(description='eMews CORE network emulator service generator tool')

parser.add_argument("emews_service_name",
                    help="Name of eMews service to be used to generate the respective CORE service")
parser.add_argument("-o", "--overwrite", action="store_true",
                    help="Overwrite existing CORE service of the same name")
parser.add_argument("--core8", action="store_true",
                    help="Generate CORE 8 compatible service - only use this if using CORE 8")

args = parser.parse_args()


def main() -> None:
    """Main function for service generator."""
    print(f"{HELP_TXT}\n")
    tool_service_gen()


def tool_service_gen() -> None:
    """CORE service generator tool."""
    emews_root = pathlib.Path(get_root_path())
    is_core8 = args.core8

    if is_core8:
        print("Generated service will be CORE 8 compatible")
        core_service_dir = 'core8_config_services'
    else:
        core_service_dir = 'core_services'

    core_service_path = emews_root.joinpath('core_emu', core_service_dir).resolve()

    if not core_service_path.exists():
        print("Could not find directory to write CORE service.  Expected location: {core_service_path}")
        return

    service_name: str = args.emews_service_name

    emews_service_path = emews_root.joinpath('services', service_name).resolve()

    if not emews_service_path.exists():
        print(f"Could not find eMews service: {service_name}.  Expected location: {emews_service_path}")
        return

    default_config_fullpath = emews_service_path.joinpath("default.yml").resolve()

    if not default_config_fullpath.exists():
        print(f"Could not find default service configuration.  Expected location: {default_config_fullpath}")
        return

    with open(default_config_fullpath) as f_config:
        config_dct = YAML().load(f_config)

    service_display_name = config_dct.get('display_name')

    if service_display_name is None:
        service_display_name = service_name

    if is_core8:
        core_service_template_name = "service_template_core8.py"
    else:
        core_service_template_name = "service_template.py"

    core_service_template = emews_root.joinpath('core_emu', core_service_template_name).read_text()
    core_service_fullpath = core_service_path.joinpath(f"{service_name}.py")

    print(f"- Using eMews service: {service_display_name}")
    print(f"- Writing CORE service to: {core_service_fullpath.resolve()}")

    is_overwrite = args.overwrite
    if is_overwrite:
        print("-- Will overwrite if CORE service already exists")
    print("\n[Generating CORE service] ...")

    service_exists = core_service_fullpath.exists()

    if service_exists and not is_overwrite:
        print(f"! {core_service_fullpath.name} not written - CORE service already exists (and overwrite disabled)")
        return

    additional_configs = ''
    additional_configs_txt = ''
    for s_file in emews_service_path.iterdir():
        if s_file.is_dir() or s_file.suffix != '.yml' and s_file.suffix != '.yaml' or s_file.name == 'default.yml':
            continue

        additional_configs = f'{additional_configs}", "{s_file.stem}'
        additional_configs_txt = f"{additional_configs_txt}\n   |- {s_file.name}"

    gen_service = core_service_template\
        .replace("__EMEWS_SERVICE_NAME__", service_name, 1)\
        .replace("__EMEWS_SERVICE_DISPLAY_NAME__", service_display_name, 1)\
        .replace("__EMEWS_CLASS_NAME__", service_name.capitalize(), 1)\
        .replace("__EMEWS_SERVICE_CONFIGS__", additional_configs, 1)

    with open(core_service_fullpath, "w") as f_service:
        f_service.write(gen_service)

    if service_exists:
        print(f"+ {core_service_fullpath.name} (existing service overwritten){additional_configs_txt}")
    else:
        print(f"+ {core_service_fullpath.name}{additional_configs_txt}")


main()
