"""Plan fijado: bootstrap estratificado pareado del test retenido, sin reentrenar."""
import argparse,hashlib,json
from pathlib import Path
import numpy as np

REPETITIONS=2000
SEED=20261126
def weighted_ap(labels,scores,weights):
    """AP con pesos enteros; agrupa empates exactamente como puntuaciones repetidas."""
    y=np.asarray(labels,dtype=np.int8);s=np.asarray(scores,dtype=np.float64);w=np.asarray(weights,dtype=np.int32)
    assert w.ndim==2 and w.shape[1]==len(y)==len(s) and np.isfinite(s).all()
    order=np.argsort(-s,kind='stable');ys=y[order];ss=s[order];ws=w[:,order]
    ends=np.r_[np.flatnonzero(ss[:-1]!=ss[1:]),len(ss)-1]
    tp=np.cumsum(ws*ys,axis=1,dtype=np.int32)[:,ends]
    total=np.cumsum(ws,axis=1,dtype=np.int32)[:,ends]
    positives=tp[:,-1];assert np.all(positives>0)
    increment=np.diff(np.concatenate([np.zeros((len(w),1),dtype=np.int32),tp],axis=1),axis=1)
    precision=np.divide(tp,total,out=np.zeros_like(tp,dtype=np.float64),where=total>0)
    return (increment*precision).sum(axis=1)/positives

def main():
    p=argparse.ArgumentParser();p.add_argument('--results',type=Path,required=True);p.add_argument('--selection',type=Path,required=True)
    p.add_argument('--splits',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    selection=json.loads(a.selection.read_text(encoding='utf8'))
    if not isinstance(selection,list) or any(type(i) is not int for i in selection) or selection!=sorted(set(selection)):
        raise ValueError('La selección debe contener índices enteros únicos y ordenados')
    selected=set(selection);assign=json.loads(a.splits.read_text(encoding='utf8'))['splits']['random']
    if any(i<0 or i>=len(assign) for i in selected):raise ValueError('Índice fuera de la asignación')
    selected_sha=hashlib.sha256(a.selection.read_bytes()).hexdigest();split_sha=hashlib.sha256(a.splits.read_bytes()).hexdigest();sources=None
    ids=sorted(i for i in selected if assign[i]=='test');assert len(ids)==2895
    labels=None;all_scores={}
    for model in ('cpg','tokens','codebert'):
        for condition in ('random','random-dedup'):
            prefix=a.results/f'{model}-{condition}';report=json.loads(prefix.with_suffix('.json').read_text(encoding='utf8'))
            assert report['seeds']==len(report['results'])==4 and report.get('status')!='in_progress'
            assert report['identity']['partition']=='random' and report['identity']['split_sha256']==split_sha
            if condition=='random-dedup':assert report['identity']['eligible_sha256']==selected_sha
            if sources is None:sources=report['identity']['sources']
            else:assert report['identity']['sources']==sources
            scores=[]
            for seed in range(4):
                pred=json.loads(prefix.with_name(prefix.name+f'-seed{seed}.json').read_text(encoding='utf8'))
                assert pred['identity']==report['identity'] and pred['seed']==seed
                by_id={r['index']:r for r in pred['rows']};assert len(by_id)==len(pred['rows']) and set(ids)<=set(by_id)
                if condition=='random-dedup':assert set(by_id)==set(ids)
                y=np.array([by_id[i]['label'] for i in ids],dtype=np.int8)
                if labels is None:labels=y
                else:assert np.array_equal(labels,y)
                scores.append(np.array([by_id[i]['score'] for i in ids],dtype=np.float64))
            all_scores[(model,condition)]=scores
    pos=np.flatnonzero(labels==1);neg=np.flatnonzero(labels==0);assert len(pos)==69 and len(pos)+len(neg)==len(ids)
    rng=np.random.default_rng(SEED);weights=np.zeros((REPETITIONS,len(ids)),dtype=np.int16)
    for i in range(REPETITIONS):
        sample=np.r_[rng.choice(pos,size=len(pos),replace=True),rng.choice(neg,size=len(neg),replace=True)]
        weights[i]=np.bincount(sample,minlength=len(ids))
    all_ones=np.ones((1,len(ids)),dtype=np.int16);out=[]
    for model in ('cpg','tokens','codebert'):
        values={};points={}
        for condition in ('random','random-dedup'):
            seeds=all_scores[(model,condition)]
            points[condition]=float(np.mean([weighted_ap(labels,s,all_ones)[0] for s in seeds]))
            # Bloques acotan la memoria sin cambiar el muestreo pareado.
            distribution=[]
            for start in range(0,REPETITIONS,100):
                distribution.extend(np.mean([weighted_ap(labels,s,weights[start:start+100]) for s in seeds],axis=0).tolist())
            values[condition]=np.asarray(distribution)
        delta=values['random-dedup']-values['random']
        out.append({'model':model,'random_mean_ap_retained_test':points['random'],'dedup_mean_ap_retained_test':points['random-dedup'],
                    'difference_dedup_minus_random':points['random-dedup']-points['random'],
                    'paired_difference_percentile_95':np.quantile(delta,[.025,.975]).tolist(),
                    'random_percentile_95':np.quantile(values['random'],[.025,.975]).tolist(),
                    'dedup_percentile_95':np.quantile(values['random-dedup'],[.025,.975]).tolist()})
    result={'test_count':len(ids),'test_positives':len(pos),'repetitions':REPETITIONS,'seed':SEED,'models':out,
            'scope':'Bootstrap percentil pareado estratificado por etiqueta, condicionado a 69 positivos y a estos cuatro modelos; presupone funciones independientes y no captura correlación por proyecto ni variación adicional entre entrenamientos.'}
    a.output.write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding='utf8');print(json.dumps(result,ensure_ascii=False))
if __name__=='__main__':main()
