import numpy as np
from scorer_kappa_next_inclusive import aggregate,fast_score_subject,weighted_accuracy_by_samples,aggregate_official_sets

def agg(acc,L):return aggregate([dict(acc=acc,L=L,sdt=0.,nSwitches=1,nUndetected=0)])
for acc in (0,49,50):assert agg(acc,.8)['Kappa']==0 and agg(acc,.8)['H']==0
assert abs(agg(75,1)['H']-2/3)<1e-12
assert abs(weighted_accuracy_by_samples([.9,.5],[1,3])-.6)<1e-12
out=aggregate_official_sets({'Acc':60.,'L':.8,'n_valid_L_subjects':12},{'Acc':70.,'L':.6,'n_valid_L_subjects':19})
assert abs(out['Acc']-(600*.6+499.2*.7)/1099.2)<1e-12
assert abs(out['L']-(12*.8+19*.6)/31)<1e-12
fs=10;gt=np.r_[np.zeros(20),np.ones(20),np.zeros(20),np.ones(40)];trial=np.zeros(len(gt))
z=fast_score_subject(gt,gt,trial,fs=fs);assert np.all(z['sdtPerSwitch']==0)
pred=np.r_[np.zeros(60),np.ones(40)];z=fast_score_subject(pred,gt,trial,fs=fs)
assert np.isinf(z['sdtPerSwitch'][0]) and z['sdtPerSwitch'][2]==0
# Inclusive endpoint: an admissible split exactly at the next switch is included.
pred=np.zeros(len(gt));pred[40:45]=1;z=fast_score_subject(pred,gt,trial,fs=fs)
assert z['sdtPerSwitch'][0]==2.0
# Sustained run may extend beyond the next switch endpoint (same trial).
pred=np.zeros(len(gt));pred[37:45]=1;z=fast_score_subject(pred,gt,trial,fs=fs)
assert np.isfinite(z['sdtPerSwitch'][0])
print('PASS kappa, sample-weighted Acc, subject-weighted L, next-switch endpoint, sustained run')
