"""Extract printed original-Suite26 summaries without inventing row-level results."""
from __future__ import annotations

import argparse
from pathlib import Path
import re
from mint_runtime import atomic_json, sha256


def section(lines, title):
    begin = next(i for i, line in enumerate(lines) if line.strip() == title)
    end = next((i for i in range(begin + 1, len(lines))
                if lines[i].startswith(('SUITE26 ', 'POOLED ', '[DONE]'))), len(lines))
    return lines[begin + 1:end]


def extract(path):
    lines = Path(path).read_text(errors='replace').splitlines()
    summary = {}
    for key, title in [('all_folds', 'SUITE26 ALL-FOLD MACRO SUMMARY — F1..F7'),
                       ('holdout', 'SUITE26 HOLDOUT MACRO SUMMARY — F6/F7')]:
        rows = []
        for line in section(lines, title):
            values = line.split()
            if len(values) == 12 and values[1].isdigit():
                rows.append(dict(model=values[0], faculties=int(values[1]),
                                 **dict(zip(['ap', 'auc', 'brier', 'ece10', 'mean_score', 'calibration_gap',
                                             'precision_at20', 'recall_at20', 'f1_at20', 'f2_at20'], map(float, values[2:])))))
        if not rows:
            raise ValueError(f'No complete printed macro rows in {title}')
        summary[key] = rows
    audits = []
    for line in section(lines, 'SUITE26 PREDECLARED PREMISE / SUCCESS AUDIT'):
        values = line.split()
        if len(values) >= 5 and re.fullmatch(r'-?\d+\.\d+', values[1]):
            audits.append(dict(premise=values[0], mean_delta_ap=float(values[1]),
                               wins=int(values[2]), cells=int(values[3]), printed_verdict=values[4]))
    summary['printed_premise_audit'] = audits
    summary['source'] = dict(name=Path(path).name, sha256=sha256(path),
                             architecture='original frozen-tree/leaf encoder with bounded score residual',
                             row_predictions_available=False,
                             limitations=['Printed fold tables may be truncated; do not recompute full macro results from those rows.',
                                          'Macro table comparisons with different faculty coverage are not matched comparisons.',
                                          'This log is not an execution or performance test of MINT.'])
    return summary


if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('log')
    p.add_argument('--out-file', required=True)
    args = p.parse_args()
    atomic_json(extract(args.log), args.out_file)
    print(f'Extracted printed summaries to {args.out_file}')
