import json
import pathlib
import re

root = pathlib.Path(__file__).resolve().parent
results = {}
for directory in sorted(root.iterdir()):
    if not directory.is_dir() or not (directory / 'build.log').exists():
        continue
    log = (directory / 'build.log').read_text()
    result = {'hardware_pass': 'hardwareTest=PASS' in log,
              'cosines': [float(x) for x in re.findall(r'referenceMinimumCosineSimilarity=([\d.]+)', log)]}
    if (directory / 'query.json').exists():
        query = json.loads((directory / 'query.json').read_text())
        result.update({key: query[key] for key in ['profileSpanCycles', 'profileSpanMs']})
    if (directory / 'state.json').exists():
        state = json.loads((directory / 'state.json').read_text())
        result['attempts'] = state['attempts']
        result['attention'] = state['recipe']['plans']['12']['dispatch']['Attention']
        result['casts'] = state['recipe']['cast_before_copies']
    errors = re.findall(r'^Error: (.*)$', log, re.M)
    if errors:
        result['errors'] = errors
    results[directory.name] = result
(root / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
for name, result in results.items():
    print(name, result.get('profileSpanCycles'), result['hardware_pass'],
          min(result['cosines'], default=None), result.get('errors', ''))
