#!/usr/bin/env python3
"""Inspect test results for timing information.

Run on a file that contains results from tests/test.py to see results.
"""


import argparse
from datetime import timedelta
import re
import statistics


def parse_args(args=None):
    parser = argparse.ArgumentParser(
        description='Summarize performance results from a test run.')
    parser.add_argument('result_file', type=argparse.FileType('r'))
    return parser.parse_args(args)


def str_to_time(time_str):
    match = re.search('([0-9]+):([0-9]+)[.]([0-9]+)', time_str)
    if not match:
        raise Exception('Badly formatted')
    minutes, seconds, milli = (int(x) for x in match.groups())
    return timedelta(minutes=minutes, seconds=seconds, milliseconds=milli)


def line_to_entry(line):
    match = re.search('([^\t ]+) +PASSED +C( n/a|.*) - R( n/a|.*)', line)
    if not match:
        return None
    test_id, compile_str, run_str = match.groups()
    compile_time = None if ' n/a' == compile_str else str_to_time(compile_str)
    run_time = None if ' n/a' == run_str else str_to_time(run_str)
    return test_id, compile_time, run_time


def iter_file_entries(open_file):
    with open_file as file:
        for line in file.readlines():
            entry = line_to_entry(line)
            if entry is not None:
                yield entry


def entry_to_compile_seconds(entry):
    _id, compile_time, _run_time = entry
    return compile_time.total_seconds()


if '__main__' == __name__:
    args = parse_args()
    mean = statistics.geometric_mean(
        map(entry_to_compile_seconds, iter_file_entries(args.result_file)))
    print('Source File:', args.result_file.name)
    print('Geometric Mean:', mean)
