#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import os
import sqlite3
import sys
import pandas as pd
from src import config


def parse_args(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('sample')
    parser.add_argument('replace')
    return parser.parse_args()


def db_tables(connection):
    """List tables in database."""
    res = pd.read_sql("select name from sqlite_master", connection)
    return res.name.values


def create_database(sample):
    """Create database with tables for targets, outcomes, and predictions."""
    db_name = f'{sample}.db'
    db_path = os.path.join(config.DATADIR, db_name)
    conn = sqlite3.connect(db_path)
    usr_name = f'users_{sample}.csv'
    usr_path = os.path.join(config.DATADIR, usr_name)
    users = pd.read_csv(usr_path)
    db_tbls = db_tables(conn)
    for tbl in ['decisions', 'outcomes', 'predictions']:
        if tbl not in db_tbls:
            users.to_sql(tbl, conn, index=False)
            conn.execute(f"create index idx_{tbl}_user_id on {tbl}(user_id)")


def main(argv=None):
    if argv is None:
        argv = sys.argv[:1]
    args = parse_args(argv)
    create_database(args.sample)


if __name__ == '__main__':
    sys.exit(main())

[((13, 13, 13, 38), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ({}, {}), '()', False, 'import argparse\n'), ((21, 10, 21, 67), 'pandas.read_sql', 'pd.read_sql', ({(21, 22, 21, 54): '"""select name from sqlite_master"""', (21, 56, 21, 66): 'connection'}, {}), "('select name from sqlite_master', connection)", True, 'import pandas as pd\n'), ((28, 14, 28, 51), 'os.path.join', 'os.path.join', ({(28, 27, 28, 41): 'config.DATADIR', (28, 43, 28, 50): 'db_name'}, {}), '(config.DATADIR, db_name)', False, 'import os\n'), ((29, 11, 29, 35), 'sqlite3.connect', 'sqlite3.connect', ({(29, 27, 29, 34): 'db_path'}, {}), '(db_path)', False, 'import sqlite3\n'), ((31, 15, 31, 53), 'os.path.join', 'os.path.join', ({(31, 28, 31, 42): 'config.DATADIR', (31, 44, 31, 52): 'usr_name'}, {}), '(config.DATADIR, usr_name)', False, 'import os\n'), ((32, 12, 32, 33), 'pandas.read_csv', 'pd.read_csv', ({(32, 24, 32, 32): 'usr_path'}, {}), '(usr_path)', True, 'import pandas as pd\n')]