"""Extrae CPG de PrimeVul por lotes con Joern; reanudación por archivo de lote.
El código se analiza como texto con Joern; nunca se compila ni ejecuta.
Intenta C y, solo para funciones sin grafo único, repite como C++.
"""
import argparse,hashlib,json,os,shutil,subprocess,sys
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--joern',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--batch-size',type=int,default=100);p.add_argument('--resume',action='store_true');a=p.parse_args()
if a.batch_size<1:p.error('batch-size debe ser positivo')
root=a.root.resolve();joern=a.joern.resolve();out=a.output.resolve();out.mkdir(parents=True,exist_ok=True)
parse=joern/('joern-parse.bat' if os.name=='nt' else 'joern-parse');export=joern/('joern-export.bat' if os.name=='nt' else 'joern-export')
if not parse.is_file() or not export.is_file():raise FileNotFoundError('Faltan joern-parse o joern-export')
converter=Path(__file__).resolve().with_name('graphml_to_functions.py');sources={}
for part in ('train','valid','test'):
 f=root/f'primevul_{part}.jsonl'
 with f.open('rb') as stream:sources[f.name]=hashlib.file_digest(stream,'sha256').hexdigest()
with converter.open('rb') as stream:converter_sha=hashlib.file_digest(stream,'sha256').hexdigest()
with parse.open('rb') as stream:joern_launcher_sha=hashlib.file_digest(stream,'sha256').hexdigest()
with Path(__file__).open('rb') as stream:extractor_sha=hashlib.file_digest(stream,'sha256').hexdigest()
manifest_path=out/'manifest.json';work=out/'work';manifest={'source_sha256':sources,'batch_size':a.batch_size,'converter_sha256':converter_sha,'extractor_sha256':extractor_sha,'joern_launcher_sha256':joern_launcher_sha,'graph_sha256':{},'coverage':{},'failed_batches':[]}
if manifest_path.exists():
 if not a.resume:raise ValueError('Ya existe el manifiesto; usa --resume o elige otra salida')
 manifest=json.loads(manifest_path.read_text(encoding='utf8'))
 if manifest['source_sha256']!=sources or manifest['batch_size']!=a.batch_size or manifest['converter_sha256']!=converter_sha or manifest['extractor_sha256']!=extractor_sha or manifest['joern_launcher_sha256']!=joern_launcher_sha:raise ValueError('Fuentes, extractor o tamaño de lote distintos')
def save():
 temp=manifest_path.with_name('manifest.json.tmp');temp.write_text(json.dumps(manifest,indent=2),encoding='utf8');temp.replace(manifest_path)
def sha(file):
 with file.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
def handle(batch,number):
 name=f'graphs-{number:06d}.jsonl';dest=out/name
 if name in manifest['graph_sha256']:
  if not dest.is_file() or sha(dest)!=manifest['graph_sha256'][name]:raise ValueError(f'Lote modificado: {name}')
  return
 if work.exists():shutil.rmtree(work)
 tmp=out/(name+'.tmp')
 try:
  def parse_group(group,ext):
   if not group:return {}
   stage=work/ext;src=stage/'src';src.mkdir(parents=True)
   for i,code in group:(src/f'{i}.{ext}').write_text(code,encoding='utf8')
   cpg=stage/'cpg.bin';export_dir=stage/'export';graph_file=stage/'graphs.jsonl'
   subprocess.run([str(parse),str(src),'--language','C','-o',str(cpg)],check=True)
   subprocess.run([str(export),str(cpg),'--repr','all','--format','graphml','--out',str(export_dir)],check=True)
   subprocess.run([sys.executable,str(converter),str(export_dir/'export.xml'),'--output',str(graph_file)],check=True)
   with graph_file.open(encoding='utf8') as stream:return {g['index']:g for g in map(json.loads,stream)}
  graphs=parse_group(batch,'c');first=len(graphs)
  missing=[(i,code) for i,code in batch if i not in graphs];fallback=parse_group(missing,'cpp');graphs.update(fallback)
  with tmp.open('w',encoding='utf8') as stream:
   for i in sorted(graphs):stream.write(json.dumps(graphs[i],ensure_ascii=False)+'\n')
  tmp.replace(dest);manifest['graph_sha256'][name]=sha(dest)
  manifest['coverage'][name]={'input':len(batch),'c_unique':first,'cpp_fallback_unique':len(fallback),'missing':len(batch)-len(graphs)}
  manifest['failed_batches']=[v for v in manifest['failed_batches'] if v!=number];save()
  print('lote',number,'funciones',len(batch),'grafos',sum(1 for _ in dest.open(encoding='utf8')),flush=True)
 except subprocess.CalledProcessError:
  if number not in manifest['failed_batches']:manifest['failed_batches'].append(number);save()
  raise
 finally:
  if work.exists():shutil.rmtree(work)
  if tmp.exists():tmp.unlink()
batch=[];index=0;number=0
for part in ('train','valid','test'):
 with (root/f'primevul_{part}.jsonl').open(encoding='utf8') as f:
  for line in f:
   row=json.loads(line);batch.append((index,row['func']));index+=1
   if len(batch)==a.batch_size:handle(batch,number);number+=1;batch=[]
if batch:handle(batch,number);number+=1
manifest['total_functions']=index;manifest['total_batches']=number;manifest['complete']=True;save()
