def description():
    desc = 'Subcommands for working with NAM forecasts.\n\n'
    desc += 'subcommands:\n'
    for cmd in iter_subcommands():
        desc += f'  {cmd:12} {subcommand_description(cmd)}\n'
    return desc


def parse_args(argv):
    import argparse

    parser = argparse.ArgumentParser(
        description=description(),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        'command',
        metavar='COMMAND',
        choices=list(iter_subcommands()),
        help='The subcommand to execute',
    )

    parser.add_argument(
        'argv',
        metavar='...',  # Matches the usage string generated by argparse.
        nargs=argparse.REMAINDER,
        help='Additional arguments are forwarded to the subcommand'
    )

    return parser.parse_args(argv)


def iter_subcommands():
    '''Iterate over the available subcommands.
    '''
    import pkgutil
    from pathlib import Path

    path = Path(__file__).parent
    for modinfo in pkgutil.iter_modules([path]):
        name = modinfo.name
        if not name.startswith('_'):
            yield name


def subcommand_description(name):
    '''Return the short description of a subcommand.
    '''
    import pkgutil
    prefix = __loader__.name
    fullname = f'{prefix}.{name}'
    loader = pkgutil.get_loader(fullname)
    mod = loader.load_module()
    desc = mod.description()
    return desc.partition('\n')[0]  # Get the first line


def call_subcommand(name, argv):
    '''Call the subcommand with the given name.
    '''
    import pkgutil
    prefix = __loader__.name
    fullname = f'{prefix}.{name}'
    loader = pkgutil.get_loader(fullname)
    mod = loader.load_module()
    mod.main(argv)


def main(argv):
    args = parse_args(argv)
    call_subcommand(args.command, args.argv)
