import json, pathlib, re
root = pathlib.Path(__file__).parent
rows = []
for path in sorted(root.glob('*layers-*'), key=lambda p: (p.name.startswith('small'), int(p.name.rsplit('-', 1)[-1]))):
    log = (path / 'run.log').read_text()
    row = dict(case=path.name, status='running')
    if (path / 'status.txt').exists():
        row.update(line.split('=',1) for line in (path / 'status.txt').read_text().splitlines())
        row['status'] = 'PASS' if row['exit_code'] == '0' else 'FAIL'
    errors = re.findall(r'^Error: (.*)$', log, re.M)
    if errors:
        row['error'] = errors[-1]
    for phase in ['lower_mid', 'select_finalist']:
        matches = re.findall(r'package build phase finished phase="'+phase+r'" elapsed_ms=(\d+)', log)
        if matches:
            row[phase+'_ms'] = int(matches[-1])
    stats = re.findall(r'region body planning searches=(\d+) cache_hits=(\d+)', log)
    if stats:
        row['body_searches'] = sum(int(s) for s,h in stats)
        row['body_cache_hits'] = sum(int(h) for s,h in stats)
    if (path / 'operations.json').exists():
        p = json.loads((path / 'operations.json').read_text())
        row['cycles'] = p['profileSpanCycles']
        row['ms'] = p['profileSpanMs']
        repeat = next((g for g in p['groups'] if g['name'] == 'operation.24'), None)
        if repeat:
            row['repeat_remainder_cycles'] = repeat['phaseCycles']
            row['average_remaining_layer_cycles'] = repeat['phaseCycles']/(int(path.name.rsplit('-',1)[-1])-1)
    accuracy = re.findall(r'referenceMaximumAbsoluteError=([\d.]+)', log)
    if accuracy:
        row['maximum_absolute_error'] = float(accuracy[-1])
    rows.append(row)
(root/'summary.json').write_text(json.dumps(rows, indent=2)+'\n')
for row in rows:
    print(json.dumps(row))
