"""Measure post-collection live bytes, reuse held-out peak increments, and score predictions."""
from pathlib import Path
from statistics import median
import json,sys,subprocess

def study():
    previous=json.loads(Path(__file__).with_name('selectif25.json').read_bytes())
    forecasts=json.loads(Path(__file__).with_name('prevision26.json').read_bytes())
    data=[]
    for forecast in forecasts:
        cap=forecast['cap']
        old=[r for r in previous if (r['cap'],r['mode'],r['tracing'])==(cap,0,1)]
        fresh=[json.loads(subprocess.check_output([sys.executable,'-B',str(Path(__file__).with_name('selectif25.py')),str(cap),'1','1'])) for _ in range(3)]
        rows=[]
        for i in (2,4,6):
            increment=median(r['bytes'][i][1]-r['bytes'][i-1][0] for r in old)
            after=[r['bytes'][i-1][0] for r in fresh];next_peak=[r['bytes'][i][1] for r in fresh]
            predicted=[x+increment for x in after];base=forecast['forecast'][i]
            rows.append(dict(read=i+1,post=after,peak=next_peak,base=base,pred=predicted,
                             error=median(y-x for x,y in zip(predicted,next_peak)),prior_error=median(next_peak)-base))
        data.append(dict(cap=cap,rows=rows))
    return data
if __name__=='__main__':print(json.dumps(study()))
