"""GNN relacional sobre grafos extraídos con Joern; no ejecuta código de funciones."""
import argparse,hashlib,json,random,re,sys
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.data import Data, Batch
from torch_geometric.loader import DataLoader
from torch_geometric.nn import RGCNConv,global_mean_pool
sys.path.insert(0,str(Path(__file__).resolve().parent))
from cpg_binary_store import BinaryStore,BinaryDataset
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--graphs',type=Path,required=True);p.add_argument('--graph-manifest',type=Path,required=True);p.add_argument('--splits',type=Path,required=True)
p.add_argument('--partition',choices=['random','grouped_near','official_temporal','project','commit'],required=True);p.add_argument('--output',type=Path,default=Path('cpg-gnn-results.json'));p.add_argument('--eligible-output',type=Path,default=Path('cpg-eligible.json'))
p.add_argument('--epochs',type=int,default=30);p.add_argument('--seeds',type=int,default=4);p.add_argument('--batch-size',type=int,default=32);p.add_argument('--hidden',type=int,default=64);p.add_argument('--checkpoint',type=Path,default=Path('cpg-gnn-checkpoint.pt'));p.add_argument('--resume',action='store_true');p.add_argument('--predictions-prefix',type=Path);p.add_argument('--attribution-index',type=int);p.add_argument('--attribution-output',type=Path,default=Path('cpg-attribution.json'));p.add_argument('--cache',type=Path,help='Cache binaria verificada de los mismos grafos');p.add_argument('--threads',type=int,default=4);p.add_argument('--device',choices=['auto','cpu','cuda'],default='auto');a=p.parse_args()
if min(a.epochs,a.seeds,a.batch_size,a.hidden,a.threads)<1:p.error('Presupuestos positivos')
hashes={};labels=[]
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='utf-8') as f:labels.extend(int(json.loads(line)['target']) for line in f)
y=np.asarray(labels);assignment=json.loads(a.splits.read_text(encoding='utf-8'))
if assignment['source_sha256']!=hashes:raise ValueError('Particiones corresponden a otro corpus')
split=assignment['splits'][a.partition]
if len(split)!=len(y):raise ValueError('Dimensiones incompatibles')
token_re=re.compile(r'[A-Za-z_][A-Za-z_0-9]*|\d+|[^\s]'); buckets=8192
edge_types={'AST':0,'CFG':1,'REACHING_DEF':2}
def bucket(s):return int.from_bytes(hashlib.blake2b(s.encode('utf-8'),digest_size=8).digest(),'little')%buckets
items={}; graph_files=sorted(a.graphs.glob('*.jsonl')) if a.graphs.is_dir() else [a.graphs]
manifest=json.loads(a.graph_manifest.read_text(encoding='utf-8'))
if not manifest.get('complete') or manifest.get('failed_batches'):raise ValueError('La extracción CPG no está completa; revisa el manifiesto')
if manifest['source_sha256']!=hashes:raise ValueError('Grafos corresponden a otro corpus')
graph_hashes={}
for file in graph_files:
 with file.open('rb') as f:graph_hashes[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
if graph_hashes!=manifest['graph_sha256']:raise ValueError('Los grafos no coinciden con el manifiesto')
store=None;cache_sha=None
if a.cache:
 cache_manifest_path=a.cache/'manifest.json';cache_manifest=json.loads(cache_manifest_path.read_text(encoding='utf-8'));cache_identity=cache_manifest['identity']
 if cache_identity['source_sha256']!=hashes or cache_identity['graph_manifest_sha256']!=hashlib.sha256(a.graph_manifest.read_bytes()).hexdigest() or cache_identity['split_sha256']!=hashlib.sha256(a.splits.read_bytes()).hexdigest():raise ValueError('La cache no corresponde a fuente, grafos o división')
 if cache_identity['trainer_sha256']!='656503a36980565def596ea753619171fe2c45d567c6c872529eb00b2829c902':raise ValueError('Parser de origen de cache desconocido')
 store=BinaryStore(a.cache,cache_identity);ids=sorted(store.records)
 if any(i<0 or i>=len(y) or store.records[i]['label']!=int(y[i]) for i in ids):raise ValueError('Índices o etiquetas de cache incompatibles')
 if hashlib.sha256(json.dumps(ids).encode('utf-8')).hexdigest()!=cache_identity['eligible_sha256']:raise ValueError('Cobertura de cache incompatible')
 cache_sha=hashlib.sha256(cache_manifest_path.read_bytes()).hexdigest()
else:
 for file in graph_files:
  with file.open(encoding='utf-8') as stream:
   for line in stream:
    g=json.loads(line);i=int(g['index'])
    if i in items or not 0<=i<len(y):raise ValueError('Índice duplicado o fuera de rango')
    feat=[]
    for node in g['nodes']:
     ts=token_re.findall(node.get('code',''))[:8];feat.append([bucket('kind:'+node['kind'])]+[bucket('token:'+v) for v in ts]+[buckets]* (8-len(ts)))
    if not feat:continue
    edges=[];types=[]
    for s,t,r in g['edges']:
     if r in edge_types:edges.extend([(s,t),(t,s)]);types.extend([edge_types[r],edge_types[r]+3])
    index=torch.tensor(edges,dtype=torch.long).T.contiguous() if edges else torch.empty((2,0),dtype=torch.long)
    items[i]=Data(x=torch.tensor(feat,dtype=torch.long),edge_index=index,edge_type=torch.tensor(types,dtype=torch.long),y=torch.tensor([y[i]],dtype=torch.float32),idx=torch.tensor([i]))
 ids=sorted(items)
all_ids=ids;a.eligible_output.write_text(json.dumps(all_ids),encoding='utf-8');part_ids={k:[i for i in all_ids if split[i]==k] for k in ('train','valid','test')}
parts={k:(BinaryDataset(store,v) if store else [items[i] for i in v]) for k,v in part_ids.items()}
if any(len(set(int(y[i]) for i in part))<2 for part in part_ids.values()):raise ValueError('Cada partición con cobertura CPG requiere ambas clases')
torch.set_num_threads(a.threads);device=torch.device(('cuda' if torch.cuda.is_available() else 'cpu') if a.device=='auto' else a.device)
if device.type=='cuda' and not torch.cuda.is_available():p.error('CUDA no disponible')
class Model(nn.Module):
 def __init__(self):
  super().__init__();self.embed=nn.Embedding(buckets+1,a.hidden,padding_idx=buckets);self.layers=nn.ModuleList([RGCNConv(a.hidden,a.hidden,6) for _ in range(3)]);self.head=nn.Linear(a.hidden,1)
 def embedded(self,b,h):
  for layer in self.layers:h=F.dropout(F.relu(layer(h,b.edge_index,b.edge_type)),p=.2,training=self.training)
  return self.head(global_mean_pool(h,b.batch)).flatten()
 def forward(self,b):return self.embedded(b,self.embed(b.x).sum(1))
def ranked(y,s):
 order=np.argsort(-s,kind='stable');sy=y[order];ss=s[order];tp=prev=i=0;ap=0.;best=(-1.,0.);pos=int(y.sum())
 while i<len(y):
  j=i+1
  while j<len(y) and ss[j]==ss[i]:j+=1
  tp+=int(sy[i:j].sum());ap+=(tp-prev)/pos*tp/j;prev=tp;f1=2*tp/(j+pos)
  if f1>best[0]:best=(f1,float(ss[i]))
  i=j
 return ap,best[1]
def predict(model,loader):
 model.eval();ys=[];scores=[]
 with torch.no_grad():
  for batch in loader:
   batch=batch.to(device);ys.extend(batch.y.cpu().tolist());scores.extend(model(batch).sigmoid().cpu().tolist())
 return np.asarray(ys),np.asarray(scores)
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*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
 return [float(max(0,center-half)),float(min(1,center+half))]
def metrics(y,s,t):
 pred=s>=t;tp=int(((y==1)&pred).sum());fp=int(((y==0)&pred).sum());fn=int(((y==1)&~pred).sum());tn=int(((y==0)&~pred).sum())
 return {'average_precision':ranked(y,s)[0],'precision':tp/(tp+fp) if tp+fp else None,'recall':tp/(tp+fn) if tp+fn else None,'precision_wilson_95':wilson(tp,tp+fp),'recall_wilson_95':wilson(tp,tp+fn),'tp':tp,'fp':fp,'fn':fn,'tn':tn}
valid=DataLoader(parts['valid'],batch_size=a.batch_size);test=DataLoader(parts['test'],batch_size=a.batch_size);results=[];saved=None;first_seed=0
identity={'sources':hashes,'graphs':graph_hashes,'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'split_sha256':hashlib.sha256(a.splits.read_bytes()).hexdigest(),'eligible_sha256':hashlib.sha256(a.eligible_output.read_bytes()).hexdigest(),'cache_manifest_sha256':cache_sha,'capture_predictions':bool(a.predictions_prefix),'partition':a.partition,'epochs':a.epochs,'seeds':a.seeds,'batch_size':a.batch_size,'hidden':a.hidden,'threads':a.threads,'device':str(device),'torch':str(torch.__version__)}
def save(data):
 a.checkpoint.parent.mkdir(parents=True,exist_ok=True);tmp=a.checkpoint.with_name(a.checkpoint.name+'.tmp');torch.save(data,tmp);tmp.replace(a.checkpoint)
if a.resume:
 saved=torch.load(a.checkpoint,map_location=device,weights_only=True)
 if saved['identity']!=identity:raise ValueError('Checkpoint de otro conjunto, partición o configuración')
 results=saved['results'];first_seed=saved['seed']
 if a.predictions_prefix:
  for previous in results:
   path=a.predictions_prefix.with_name(a.predictions_prefix.name+f"-seed{previous['seed']}.json")
   if not path.is_file():raise ValueError('Faltan predicciones de una semilla ya terminada')
   prediction=json.loads(path.read_text(encoding='utf8'))
   if prediction['identity']!=identity or prediction['seed']!=previous['seed']:raise ValueError('Predicciones previas incompatibles')
for seed in range(first_seed,a.seeds):
 torch.manual_seed(seed);gen=torch.Generator().manual_seed(seed);train=DataLoader(parts['train'],batch_size=a.batch_size,shuffle=True,generator=gen);model=Model().to(device);opt=torch.optim.Adam(model.parameters(),lr=.001);best=-1.;best_epoch=0;state=None;first_epoch=1
 if saved is not None and saved['seed']==seed and saved['model'] is not None:
  model.load_state_dict(saved['model']);opt.load_state_dict(saved['optimizer']);best=saved['best'];best_epoch=saved['best_epoch'];state=saved['best_model'];first_epoch=saved['epoch']+1;torch.set_rng_state(saved['rng_cpu'].cpu());gen.set_state(saved['loader_rng'].cpu())
  if device.type=='cuda':torch.cuda.set_rng_state_all([v.cpu() for v in saved['rng_cuda']])
 for epoch in range(first_epoch,a.epochs+1):
  model.train()
  for batch in train:
   batch=batch.to(device);opt.zero_grad();loss=F.binary_cross_entropy_with_logits(model(batch),batch.y);loss.backward();opt.step()
  vy,vs=predict(model,valid);ap,_=ranked(vy,vs)
  if ap>best:best=ap;best_epoch=epoch;state={k:v.detach().clone() for k,v in model.state_dict().items()}
  save({'identity':identity,'seed':seed,'epoch':epoch,'model':model.state_dict(),'optimizer':opt.state_dict(),'best':best,'best_epoch':best_epoch,'best_model':state,'results':results,'rng_cpu':torch.get_rng_state(),'loader_rng':gen.get_state(),'rng_cuda':torch.cuda.get_rng_state_all() if device.type=='cuda' else None})
 model.load_state_dict(state);vy,vs=predict(model,valid);threshold=ranked(vy,vs)[1];ty,ts=predict(model,test);row={'seed':seed,'best_epoch':best_epoch,'valid_average_precision':best,'threshold_selected_on_valid':threshold,'test':metrics(ty,ts,threshold)};results.append(row);print(json.dumps(row),flush=True);a.output.write_text(json.dumps({'status':'in_progress','results':results},indent=2),encoding='utf-8')
 if a.predictions_prefix:
  ids=part_ids['test'];assert len(ids)==len(ty)==len(ts)
  dest=a.predictions_prefix.with_name(a.predictions_prefix.name+f'-seed{seed}.json');dest.parent.mkdir(parents=True,exist_ok=True);tmp=dest.with_name(dest.name+'.tmp')
  tmp.write_text(json.dumps({'identity':identity,'seed':seed,'threshold':threshold,'rows':[{'index':i,'label':int(label),'score':float(score)} for i,label,score in zip(ids,ty,ts)]}),encoding='utf8');tmp.replace(dest)
 best_path=a.checkpoint.with_name(f'{a.checkpoint.stem}-seed{seed}-best.pt');temp=best_path.with_name(best_path.name+'.tmp');torch.save({'identity':identity,'seed':seed,'epoch':best_epoch,'model':model.state_dict(),'threshold':threshold},temp);temp.replace(best_path)
 save({'identity':identity,'seed':seed+1,'epoch':0,'model':None,'optimizer':None,'best':None,'best_epoch':0,'best_model':None,'results':results,'rng_cpu':torch.get_rng_state(),'loader_rng':None,'rng_cuda':torch.cuda.get_rng_state_all() if device.type=='cuda' else None});saved=None
report={'model':'3-layer RGCN mean-pool, 3 relations + inverses','identity':identity,'partition':a.partition,'sources':hashes,'graph_files':graph_hashes,'sizes':{k:len(v) for k,v in parts.items()},'epochs_max':a.epochs,'seeds':a.seeds,'results':results}
a.output.write_text(json.dumps(report,indent=2),encoding='utf-8');print(json.dumps(report,indent=2),flush=True)
if a.attribution_index is not None:
 if a.attribution_index not in all_ids:raise ValueError('No hay grafo para el índice solicitado')
 best_path=a.checkpoint.with_name(f'{a.checkpoint.stem}-seed{a.seeds-1}-best.pt');best_saved=torch.load(best_path,map_location=device,weights_only=True)
 if best_saved['identity']!=identity:raise ValueError('Pesos de atribución no corresponden a esta ejecución')
 model=Model().to(device);model.load_state_dict(best_saved['model']);model.eval();b=Batch.from_data_list([store.get(a.attribution_index) if store else items[a.attribution_index]]).to(device)
 base=model.embed(b.x).sum(1).detach();total=torch.zeros_like(base);steps=64
 for k in range(1,steps+1):
  h=(base*(k/steps)).detach().requires_grad_(True);value=model.embedded(b,h);total+=torch.autograd.grad(value.sum(),h)[0]
 attribution=(base*total/steps).sum(-1).detach().cpu();zero=torch.zeros_like(base)
 with torch.no_grad(): logit=float(model.embedded(b,base)[0]);baseline=float(model.embedded(b,zero)[0])
 with best_path.open('rb') as f:best_sha=hashlib.file_digest(f,'sha256').hexdigest()
 out={'index':a.attribution_index,'partition':split[a.attribution_index],'seed':best_saved['seed'],'epoch':best_saved['epoch'],
      'identity':identity,'best_checkpoint_sha256':best_sha,
      'method':'integrated gradients en embedding, base cero, 64 pasos','logit':logit,'baseline_logit':baseline,
      'attributions':attribution.tolist(),'sum_attributions':float(attribution.sum()),'completeness_residual':float((logit-baseline)-attribution.sum())}
 a.attribution_output.write_text(json.dumps(out,indent=2),encoding='utf-8');print('atribución',a.attribution_output,'residuo',out['completeness_residual'],flush=True)
