"""
Universal module launcher entry script.

This provides compatibility to the core to launch the worker subprocesses the same way in a normal python-interpreter
environment and a frozen deployment by cx_Freeze.
"""
import argparse
import importlib
import sys
from types import ModuleType
from typing import List

from clarabot_nano import __version__
from clarabot_nano.common.i18n import LOCALIZATION

LOCALIZATION.install()


class ClarabotNanoLauncher(object):
    """
    A simple object to support customizing the arguments and overriding the launch targets implicitly for development.
    """

    @classmethod
    def get_launch_targets(cls) -> List[str]:
        targets = [
            "clarabot_nano.core",
            "clarabot_nano.gateway",
            "clarabot_nano.indexer",
            "clarabot_nano.server.general",
            "clarabot_nano.server.fstx",
            "clarabot_nano.control",
        ]
        if sys.platform.startswith("win"):
            # signal transmitter utility to child processes for graceful termination
            targets.append("clarabot_nano.utility.subprocess.winterrupt")
        return targets

    @classmethod
    def get_name(cls) -> str:
        return "Clarabot Nano"

    @classmethod
    def parse_target_module(cls) -> ModuleType:
        launch_targets = cls.get_launch_targets()
        parser = argparse.ArgumentParser(f"{cls.get_name()} - Launcher")
        parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
        parser.add_argument(
            "-m",
            default=launch_targets[0],
            choices=launch_targets,
            help="module to launch; "
            "used by the core process to spawn the different workers; "
            "users normally do not specify this argument",
        )
        args, remaining_args = parser.parse_known_args()

        sys.argv[1:] = remaining_args if not remaining_args or remaining_args[0] != "--" else remaining_args[1:]
        return importlib.import_module(".__main__", args.m)


if __name__ == "__main__":
    ClarabotNanoLauncher.parse_target_module().main()
