"""Selecciona una cohorte reproducible sin usar etiquetas para la selección.

Se muestrea dentro de las tres particiones oficiales, proporcionalmente a su
tamaño, entre funciones con proyecto y commit identificados. No ejecuta código.
Un archivo opcional de particiones de la auditoría completa se proyecta a la
cohorte para mantener juntos los duplicados detectados en todo el corpus.
"""
import argparse,hashlib,json,random,sys
from pathlib import Path

p=argparse.ArgumentParser()
p.add_argument('--root',type=Path,required=True)
p.add_argument('--output',type=Path,required=True)
p.add_argument('--size',type=int,default=30000)
p.add_argument('--seed',type=int,default=20261126)
p.add_argument('--full-splits',type=Path)
a=p.parse_args()
if a.size<3:p.error('El tamaño debe ser al menos tres')
parts=('train','valid','test');rows={};source_sha={};eligible={};offset=0
for part in parts:
    file=a.root/f'primevul_{part}.jsonl'
    with file.open('rb') as f:source_sha[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
    with file.open(encoding='utf8') as f:rows[part]=[json.loads(line) for line in f]
    eligible[part]=[i for i,row in enumerate(rows[part]) if row.get('project') and row.get('commit_id')]
    offset+=len(rows[part])
total=sum(map(len,eligible.values()))
if a.size>total:raise ValueError('La cohorte excede las funciones con proyecto y commit')
raw={part:a.size*len(eligible[part])/total for part in parts}
allocation={part:int(raw[part]) for part in parts}
for part in sorted(parts,key=lambda s:raw[s]-allocation[s],reverse=True)[:a.size-sum(allocation.values())]:allocation[part]+=1
rng=random.Random(a.seed);selected={part:sorted(rng.sample(eligible[part],allocation[part])) for part in parts}
a.output.mkdir(parents=True,exist_ok=True);original_indices=[];cohort_sha={};stats={};offset=0
for part in parts:
    file=a.output/f'primevul_{part}.jsonl';temp=file.with_name(file.name+'.tmp');chosen=selected[part]
    with temp.open('w',encoding='utf8',newline='\n') as f:
        for i in chosen:
            row=dict(rows[part][i]);row['_original_index']=offset+i
            f.write(json.dumps(row,ensure_ascii=False)+'\n');original_indices.append(offset+i)
    with temp.open('rb') as f:cohort_sha[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
    if file.exists():
        with file.open('rb') as f:existing_sha=hashlib.file_digest(f,'sha256').hexdigest()
        if existing_sha!=cohort_sha[file.name]:
            temp.unlink();raise ValueError(f'La cohorte existente difiere; usa otro directorio: {file}')
        temp.unlink()
    else:temp.replace(file)
    stats[part]={'eligible_population':len(eligible[part]),'selected':len(chosen),
                 'positive':sum(rows[part][i]['target']==1 for i in chosen),
                 'projects':len({rows[part][i]['project'] for i in chosen}),
                 'commits':len({(rows[part][i]['project'],rows[part][i]['commit_id']) for i in chosen})}
    offset+=len(rows[part])
manifest={'source_sha256':source_sha,'cohort_sha256':cohort_sha,'selection':'uniforme sin reemplazo por partición oficial; solo proyecto y commit identificados, sin consultar etiqueta',
          'seed':a.seed,'size':a.size,'python':sys.version,'selector_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
          'stats':stats,'limitations':['El corpus no suministra fechas individuales; se conservan las particiones temporales oficiales.']}
(a.output/'cohort-manifest.json').write_text(json.dumps(manifest,indent=2,ensure_ascii=False),encoding='utf8')
if a.full_splits:
    full=json.loads(a.full_splits.read_text(encoding='utf8'))
    if full['source_sha256']!=source_sha:raise ValueError('Particiones del corpus completo no coinciden con sus hashes')
    projected={name:[values[i] for i in original_indices] for name,values in full['splits'].items()}
    full_split_sha=hashlib.sha256(a.full_splits.read_bytes()).hexdigest()
    (a.output/'cohort.splits.json').write_text(json.dumps({'source_sha256':cohort_sha,'full_source_sha256':source_sha,
        'full_splits_sha256':full_split_sha,'selection_seed':a.seed,'splits':projected},ensure_ascii=False),encoding='utf8')
print(json.dumps(manifest,indent=2,ensure_ascii=False))
