"""Plot observed learning curves and report completed pilot runs."""
from __future__ import annotations

import json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from .data.protocol import write_json


def report(root='outputs/learning_120_v4'):
    root=Path(root);runs=[]
    fig,axes=plt.subplots(1,2,figsize=(10,4.4))
    colors={'yolo26s':'#197a83','pallet_yolo26':'#ad572f'}
    for metric_path in sorted(root.rglob('metrics.jsonl')):
        path=metric_path.parent;name=path.parent.name
        rows=[json.loads(line) for line in metric_path.read_text().splitlines()]
        if not (path/'completed.json').exists() or not (path/'val.json').exists():continue
        result=json.loads((path/'val.json').read_text())
        axes[0].plot([r['epoch']+1 for r in rows],[r['train_loss'] for r in rows],label=name,color=colors.get(name))
        axes[1].plot([r['epoch']+1 for r in rows],[r['validation']['AP50_95']*100 for r in rows],label=name,color=colors.get(name))
        runs.append({'name':name,'epochs':len(rows),'AP50':result['AP50'],'AP75':result['AP75'],
                     'AP50_95':result['AP50_95'],'reference_coverage':result['reference_coverage'],
                     'run_path':str(path)})
    axes[0].set_ylabel('Training loss');axes[1].set_ylabel('Validation AP50:95 (%)')
    for axis in axes:
        axis.set_xlabel('Epoch');axis.grid(alpha=.2);axis.legend(frameon=False)
    fig.suptitle('Preliminary learning check | single seed | independent machine reference',fontsize=10)
    fig.tight_layout();fig.savefig(root/'learning_curves.png',dpi=160);plt.close(fig)
    result={'status':'preliminary, 66 scored source frames; not final model selection',
             'test_set_scored':False,'runs':runs,
             'limitations':['Only one seed and a small training subset.',
                            '44/150 validation frames ignored as ambiguous.',
                            'Most current scoring frames lack verified metric depth.',
                            'Initial FP16 scaler warmup produced skipped steps; future recipe uses BF16.']}
    write_json(root/'summary.json',result)
    return result


if __name__=='__main__':print(json.dumps(report()))
