"""Audita cobertura de grafos por partición y clase sin ejecutar código."""
import argparse,hashlib,json
from pathlib import Path

p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--graphs',type=Path,required=True)
p.add_argument('--splits',type=Path,required=True);p.add_argument('--output',type=Path,default=Path('coverage.json'));a=p.parse_args()
labels=[];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:labels.extend(int(json.loads(line)['target']) for line in f)
assignment=json.loads(a.splits.read_text(encoding='utf8'))
if assignment['source_sha256']!=hashes:raise ValueError('Particiones de otra fuente')
manifest=json.loads((a.graphs/'manifest.json').read_text(encoding='utf8'))
if not manifest.get('complete') or manifest.get('failed_batches') or manifest['source_sha256']!=hashes:raise ValueError('Extracción incompleta o de otra fuente')
records={};files=sorted(a.graphs.glob('*.jsonl'));graph_sha={}
for file in files:
    with file.open('rb') as f:graph_sha[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
    with file.open(encoding='utf8') as f:
        for line in f:
            g=json.loads(line);i=int(g['index'])
            if i in records or not 0<=i<len(labels):raise ValueError('Índice de grafo duplicado o inválido')
            relations={edge[2] for edge in g['edges']}
            records[i]={'ext':g['source_ext'],'AST':'AST' in relations,'CFG':'CFG' in relations,'REACHING_DEF':'REACHING_DEF' in relations}
if graph_sha!=manifest['graph_sha256']:raise ValueError('Hashes de grafos no coinciden con el manifiesto')
report={}
for name,split in assignment['splits'].items():
    if len(split)!=len(labels):raise ValueError('Longitud de división incorrecta')
    report[name]={}
    for part in ('train','valid','test'):
        report[name][part]={}
        for label in (0,1):
            ids=[i for i in range(len(labels)) if split[i]==part and labels[i]==label];available=[records[i] for i in ids if i in records]
            report[name][part][str(label)]={'input':len(ids),'covered':len(available),'missing':len(ids)-len(available),
                'AST':sum(r['AST'] for r in available),'CFG':sum(r['CFG'] for r in available),'REACHING_DEF':sum(r['REACHING_DEF'] for r in available),
                'c':sum(r['ext']=='.c' for r in available),'cpp':sum(r['ext']=='.cpp' for r in available)}
out={'source_sha256':hashes,'graph_sha256':graph_sha,'splits_sha256':hashlib.sha256(a.splits.read_bytes()).hexdigest(),'partitions':report,
     'note':'Presencia de aristas no garantiza análisis completo; ausencia tampoco identifica la causa.'}
a.output.write_text(json.dumps(out,indent=2,ensure_ascii=False),encoding='utf8');print(json.dumps(report,indent=2))
