"""Descriptive diagnostics, not new detector tuning or confirmatory tests."""
import json
from pathlib import Path
import numpy as np
r=json.loads(Path('results/R1.json').read_text());rows=json.loads(Path('results/injections.json').read_text())
rows=[x for x in rows if x['split']=='evaluation'];control=r['selected_method']
# Dots in method names are avoided in these result keys for journal result references.
def flag(q,m):
    t=r['evaluation_matched'][m]['threshold']
    return q['scores'][m]>t and q['local_null'][m]<=t
b=np.array([flag(x,'baseline') for x in rows]);c=np.array([flag(x,control) for x in rows]);g=np.array([flag(x,'gap_only') for x in rows])
out={'gained':int(np.sum(c&~b)),'lost':int(np.sum(b&~c)),'both':int(np.sum(b&c)),'neither':int(np.sum(~b&~c)),'gap_only_recovered':int(g.sum()),'gap_only_pct':round(100*g.mean(),1),'control_vs_gap_gained':int(np.sum(c&~g)),'control_vs_gap_lost':int(np.sum(g&~c)), 'subgroups':{}}
for name,edges in [('peak_ppm',[0,500,1500,5000,1e9]),('duration_hours',[0,6,12,18,1e9])]:
    a=[]
    for lo,hi in zip(edges[:-1],edges[1:]):
        sel=np.array([lo<=x[name]<hi for x in rows]);n=int(sel.sum())
        a.append({'lower':lo,'upper':hi if hi<1e9 else None,'injections':n,'baseline_pct':round(float(100*b[sel].mean()),1) if n else None,'control_pct':round(float(100*c[sel].mean()),1) if n else None})
    out['subgroups'][name]=a
out['all_development_methods']=[{'method':m,'recovery_pct':round(z['recovery_pct'],1)} for m,z in r['development'].items()]
out['all_evaluation_methods']=[{'method':m,'recovery_pct':round(z['recovery_pct'],1)} for m,z in r['evaluation_matched'].items()]
out['sensitivity']=[{'background_pct':round(100*float(a),1),'baseline_pct':round(v['baseline']['recovery_pct'],1),'control_pct':round(v[control]['recovery_pct'],1),'delta_pp':round(v[control]['recovery_pct']-v['baseline']['recovery_pct'],1)} for a,v in r['operating_points'].items()]
Path('results/R2.json').write_text(json.dumps(out,indent=2))
print(json.dumps(out,indent=2))
