# -*- coding: utf-8 -*-
"""Usage:
  avtograf [init|run] [--src <PATH>] [--debug] [--version]

--src  path to the data

Support: leroy, n-bar
"""
from docopt import docopt
from os.path import exists
import traceback as tb
from const import VERSION, LOG_FILE, SRC_NAME, DB_NAME, TBL_NAME, TASK_NAME, DST_DIR
from tsv2db import main as cmd_init
from avtograf import main as cmd_run


def cmds(args):
    print args
    if not args['init'] and not args['run']:
        if exists(DB_NAME) and exists(TASK_NAME):
            args['init'] = False
            args['run'] = True
        else:
            args['init'] = True
            args['run'] = False

    if args['init']:
        print 'init...', cmd_init(DB_NAME, TBL_NAME, args['<PATH>'] or SRC_NAME, TASK_NAME)
        print 'done'

    if args['run']:
        print DST_DIR
        print 'run...', cmd_run(DB_NAME, TASK_NAME, DST_DIR)
        print 'done'

    print 'exit'


def main():
    try:
        args = docopt(__doc__, version=VERSION)
        if args.get('--debug'):
            with open(LOG_FILE, 'w') as f:
                f.write('\nVERSION\n:%s\n' % VERSION)
                f.write('\nCLI ARGS\n:%r\n' % args)
        cmds(args)

    except Exception as err:
        print 'error: %s' % err.message
        with open(LOG_FILE, 'a') as f:
            tb.print_exc(file=f)


if __name__ == '__main__':
    main()
