#!/usr/bin/python
import sys
import os
from l3tlib.config import L3tConfig


def format_aliases(commands):
    longest = max(len(cmd) for cmd in commands)
    padding = longest + 10
    lines = ["   %s\t%s" % (command.ljust(padding), ", ".join(aliases))
             for command, aliases in commands.iteritems()]
    return "\n".join(sorted(lines))


def usage(commands):
    print """\
l3t -- helper tools for L3 work

Before proceeding, please ensure you have added your API key to
~/.l3t.conf.

Basic commands:        (l3t subcommand aliases)

%s

For more information run l3t <SUBCOMMAND> --help.
""" % (format_aliases(commands))


def wrong_usage(commands):
    usage(commands)
    sys.exit(1)


def pick_command(subcommand, commands):
    candidates = {}
    for cmd, aliases in commands.iteritems():
        for alias in aliases:
            if alias.startswith(subcommand):
                candidates[cmd] = alias
    if not candidates:
        wrong_usage(commands)
    elif len(candidates) > 1:
        joined = ", ".join(candidate for cmd, candidate in
                           candidates.iteritems())
        sys.stderr.write("ambiguous subcommand for %s\n" % (joined))
        sys.exit(1)
    return candidates.keys()[0]


def main():
    config = L3tConfig()
    commands = config.get_commands()
    if len(sys.argv) < 2:
        wrong_usage(commands)
    else:
        dir = os.path.dirname(__file__)
        cmd = pick_command(sys.argv[1], commands)
        prog = os.path.join(dir, cmd)
        if os.path.exists(prog):
            args = [cmd] + sys.argv[2:]
            os.execv(prog, args)
        else:
            wrong_usage(commands)


if __name__ == "__main__":
    main()
