import argparse
import asyncio
import logging
import sys

from . import cli, config

log = logging.getLogger(__package__)


def getargs():
    parser = argparse.ArgumentParser(prog="unwind", allow_abbrev=False)
    commands = parser.add_subparsers(title="commands", metavar="COMMAND", dest="mode")

    for module in cli.modules:
        help_, *descr = module.help.splitlines()
        cmd = commands.add_parser(
            module.name,
            help=help_,
            description="\n".join(descr) or help_,
            allow_abbrev=False,
        )
        module.add_args(cmd)

    try:
        args = parser.parse_args()
    except TypeError:
        parser.print_usage()
        raise

    if args.mode is None:
        parser.print_help()
        sys.exit(1)

    return args


def main():
    logging.basicConfig(
        format="%(asctime)s.%(msecs)03d [%(name)s:%(process)d] %(levelname)s: %(message)s",
        datefmt="%H:%M:%S",
        # level=config.loglevel,
    )
    log.setLevel(config.loglevel)
    log.debug(f"Log level: {config.loglevel}")

    args = getargs()

    modes = {m.name: m.main for m in cli.modules}
    if handler := modes.get(args.mode):
        asyncio.run(handler(args))


main()
