import sys
import json
import codecs
import argparse

from balancer.production.x.extract_backends_and_patterns.lib import get_modules_backends


def main():
    parser = argparse.ArgumentParser(description='Convert lua balancer config to json')
    parser.add_argument('infile', type=str, help='original lua config')
    parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=sys.stdout, help='output file')
    parser.add_argument('--dump-tree', action='store_true', help='enable pretty printing')
    parser.add_argument('--pretty', action='store_true', help='enable pretty printing')
    args = parser.parse_args()

    config = codecs.open(args.infile, encoding='utf-8').read()

    indent = 2 if args.pretty else None

    with args.outfile as f:
        json.dump(get_modules_backends(config, args.dump_tree, fill_backends=True), f, indent=indent)

if __name__ == '__main__':
    main()
