"""Render comparable weak-label metrics separately for each evaluation protocol."""
from __future__ import annotations

import html
import math


def weak_result(record):
    return record.get('common_grid_weak_fit') if 'common_grid_weak_fit' in record else record.get('weak_fit')


def weak_model_tables(rows):
    protocols = list(dict.fromkeys(['train_all', 'leave_one_design_out'] + [r['protocol'] for r in rows]))
    titles = {'train_all': 'Training fit', 'leave_one_design_out': 'Held-out-design evaluation',
              'per_design': 'Per-design training fit'}
    metrics = [('bce', 'BCE ↓', min), ('average_precision', 'AP ↑', max), ('iou', 'IoU ↑', max)]
    tables = []
    for protocol in protocols:
        group = [r for r in rows if r['protocol'] == protocol]
        if not group:
            continue
        best = {}
        for key, _, choose in metrics:
            values = [r[key] for r in group if r.get(key) is not None and math.isfinite(r[key])]
            best[key] = choose(values) if values else None
        body = []
        show_size = any(row.get('input_size') for row in group)
        for row in group:
            cells = [html.escape(row['model_id']), str(row['datasets'])]
            if show_size: cells.insert(1, html.escape(row.get('input_size', '—')))
            for key, _, _ in metrics:
                value = row.get(key)
                cell = f'{value:.4f}' if value is not None and math.isfinite(value) else '—'
                if best[key] is not None and value is not None and math.isclose(value, best[key], rel_tol=1e-9, abs_tol=1e-12):
                    cell = f'<strong>{cell}</strong>'
                cells.append(cell)
            body.append('<tr>' + ''.join(f'<td>{cell}</td>' for cell in cells) + '</tr>')
        tables.append(f'<section class="weak-model-protocol" data-protocol="{html.escape(protocol)}">'
                      f'<h3>{html.escape(titles.get(protocol, protocol))} · <code>{html.escape(protocol)}</code></h3>'
                      '<div style="overflow:auto"><table><thead><tr><th scope="col">Model</th>'
                      + ('<th scope="col">Input size</th>' if show_size else '') + '<th scope="col">Datasets</th>'
                      + ''.join(f'<th scope="col">{label}</th>' for _, label, _ in metrics)
                      + '</tr></thead><tbody>' + ''.join(body) + '</tbody></table></div></section>')
    return ('<p>Bold marks the best value in each metric column within its table, including ties. '
            'Lower BCE is better; higher AP and IoU are better.</p>' + ''.join(tables)) if tables else ''
