"""Desglosa errores por CWE disponible sin ejecutar funciones del corpus."""
import argparse,collections,hashlib,json,math,re
from pathlib import Path

p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--splits',type=Path,required=True)
p.add_argument('--eligible',type=Path,required=True);p.add_argument('--predictions',type=Path,required=True)
p.add_argument('--min-support',type=int,default=10);p.add_argument('--min-positives',type=int,default=10);p.add_argument('--output',type=Path,default=Path('errores-cwe.json'));a=p.parse_args()
if min(a.min_support,a.min_positives)<1:p.error('Los mínimos deben ser positivos')
rows=[];hashes={}
for part in ('train','valid','test'):
    file=a.root/f'primevul_{part}.jsonl'
    with file.open('rb') as f:hashes[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
    with file.open(encoding='utf8') as f:rows.extend(json.loads(line) for line in f)
assignment=json.loads(a.splits.read_text(encoding='utf8'));pred=json.loads(a.predictions.read_text(encoding='utf8'));identity=pred['identity']
if assignment['source_sha256']!=hashes or identity['sources']!=hashes:raise ValueError('Fuentes incompatibles')
if identity['split_sha256']!=hashlib.sha256(a.splits.read_bytes()).hexdigest() or identity['eligible_sha256']!=hashlib.sha256(a.eligible.read_bytes()).hexdigest():raise ValueError('División o cobertura incompatibles')
split=assignment['splits'][identity['partition']];eligible=set(json.loads(a.eligible.read_text(encoding='utf8')))
if len(split)!=len(rows) or any(not isinstance(i,int) or not 0<=i<len(rows) for i in eligible):raise ValueError('Índices o dimensión inválidos')
expected={i for i in eligible if 0<=i<len(rows) and split[i]=='test'}
seen=set();counts=collections.defaultdict(lambda:{'n':0,'tp':0,'fp':0,'fn':0,'tn':0})
threshold=float(pred['threshold'])
if not math.isfinite(threshold) or not 0<=threshold<=1:raise ValueError('Umbral fuera de [0,1]')
for item in pred['rows']:
    i=int(item['index']);score=float(item['score']);label=int(item['label'])
    if i in seen or i not in expected or label!=int(rows[i]['target']) or not math.isfinite(score) or not 0<=score<=1:raise ValueError('Predicción duplicada o incompatible')
    seen.add(i);code='tp' if label and score>=threshold else ('fn' if label else ('fp' if score>=threshold else 'tn'))
    raw=rows[i].get('cwe') or [];raw=[raw] if isinstance(raw,str) else raw
    tags={v for v in raw if isinstance(v,str) and re.fullmatch(r'CWE-\d+',v)} or {'sin_etiqueta'}
    for tag in tags:counts[tag]['n']+=1;counts[tag][code]+=1
if seen!=expected:raise ValueError('Faltan predicciones de test')
def wilson(success,n):
    if n==0:return None
    z=1.959963984540054;p=success/n;den=1+z*z/n;center=(p+z*z/(2*n))/den;half=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
    return [max(0,center-half),min(1,center+half)]
groups={tag:value for tag,value in sorted(counts.items()) if value['n']>=a.min_support and value['tp']+value['fn']>=a.min_positives}
for v in groups.values():
    v['precision']=v['tp']/(v['tp']+v['fp']) if v['tp']+v['fp'] else None
    v['recall']=v['tp']/(v['tp']+v['fn']) if v['tp']+v['fn'] else None
    v['precision_wilson_95']=wilson(v['tp'],v['tp']+v['fp']);v['recall_wilson_95']=wilson(v['tp'],v['tp']+v['fn'])
out={'partition':identity['partition'],'seed':pred['seed'],'threshold_selected_on_valid':threshold,'test_functions':len(seen),
     'min_support':a.min_support,'min_positives':a.min_positives,'groups':groups,'groups_below_support':len(counts)-len(groups),
     'note':'CWE proviene de metadatos del caso; puede no describir cada función. Las categorías se solapan y no deben sumarse. Wilson presupone independencia y probabilidad común; no implica causalidad.'}
a.output.write_text(json.dumps(out,indent=2,ensure_ascii=False),encoding='utf8');print(json.dumps(out,indent=2,ensure_ascii=False))
