#!/usr/bin/env python3

import argparse
import local_learning
import logging
import datetime
import os

logger = logging.getLogger()

from local_learning.models.loopy.search import search_harness
from local_learning.models.loopy import postgres

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Run checks on loopy.factory sampled models.')
    parser.add_argument('--verbose', '-v', action='count', default=0)
    parser.add_argument('--quiet', '-q', action='store_true', default=False, help='Don\'t even log errors.')
    parser.add_argument('--debug-exceptions', action='store_true', default=False, help='Don\'t ignore exceptions so they can be debugged.')
    parser.add_argument('--limit', type=int, default=None, help='Max number of times to run search.')
    parser.add_argument('--seed', type=int, default=None, help='Random seed to use; defaults to None (helpful for debugging).')
    parser.add_argument('--postgres', type=str, default=None, help='Log results to this postgres database. Can also pass as environment variable.')
    parser.add_argument('--no-tests', action='store_true', default=False, help='Don\'t actually run tests, just generate code and save it.')

    args = parser.parse_args()

    if args.verbose == 0:
        logger.setLevel(logging.ERROR)
    elif args.verbose == 1:
        logger.setLevel(logging.INFO)
    elif args.verbose > 1:
        logger.setLevel(logging.DEBUG)

    if args.quiet:
        logger.setLevel(logging.CRITICAL)

    if args.seed is not None:
        import numpy as np
        import random
        random.seed(args.seed)
        np.random.seed(args.seed)

    local_learning.debug_exceptions = args.debug_exceptions

    postgres_uri = args.postgres or os.environ.get('PG_URI', None)

    for harness_generator, harness_code, results in search_harness(limit=args.limit, no_tests=args.no_tests):
        average_score = sum(results) / len(results)
        logger.info('got score {} with results {}'.format(average_score, results))
        if postgres_uri:
            if average_score <= 0.6:
                harness_generator = None
                harness_code = ''
            postgres.save(postgres_uri, score=average_score, code=harness_code, blob=harness_generator)
