"""Construye una cache CPG binaria reanudable sin retener todos los grafos."""
import argparse
import hashlib
import json
from pathlib import Path
import torch
from cpg_offset_dataset import OffsetStore
from cpg_binary_cache import build_cache

p=argparse.ArgumentParser()
p.add_argument('--root',type=Path,required=True,help='Directorio con primevul_train/valid/test.jsonl')
p.add_argument('--graphs',type=Path,required=True,help='Directorio de JSONL de grafos')
p.add_argument('--graph-manifest',type=Path,required=True)
p.add_argument('--splits',type=Path,required=True)
p.add_argument('--output',type=Path,required=True,help='Directorio nuevo o progreso compatible')
a=p.parse_args();torch.set_num_threads(1)
manifest=json.loads(a.graph_manifest.read_text(encoding='utf-8'))
assignment=json.loads(a.splits.read_text(encoding='utf-8'))
if not manifest.get('complete') or manifest.get('failed_batches'):raise ValueError('Extracción incompleta')
labels=[];sources={}
for part in ('train','valid','test'):
    path=a.root/f'primevul_{part}.jsonl'
    with path.open('rb') as stream:sources[path.name]=hashlib.file_digest(stream,'sha256').hexdigest()
    with path.open(encoding='utf-8') as stream:labels.extend(int(json.loads(line)['target']) for line in stream)
if sources!=manifest['source_sha256'] or sources!=assignment['source_sha256']:raise ValueError('Fuentes incompatibles')
def sha(path):
    with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
encoder=Path(__file__).with_name('cpg_offset_dataset.py')
builder=Path(__file__).with_name('cpg_binary_cache.py')
if sha(encoder)!='6565338e0e339af31025afe97efcf21bdc68be1849abc024dfd382dc8df794f0':raise ValueError('Versión desconocida del codificador de grafos')
if sha(builder)!='5b672cee0b03a2d22720d3475c146239c9539b69c9e1dcb02f8c6d90ed4e3052':raise ValueError('Versión desconocida del constructor binario')
store=OffsetStore(a.graphs,manifest,labels)
try:
    ids=sorted(store.locations)
    identity={'format_version':1,'graph_manifest_sha256':sha(a.graph_manifest),'source_sha256':sources,
              'eligible_sha256':hashlib.sha256(json.dumps(ids).encode('utf-8')).hexdigest(),
              'split_sha256':sha(a.splits),
              'trainer_sha256':'656503a36980565def596ea753619171fe2c45d567c6c872529eb00b2829c902',
              'encoder_sha256':sha(encoder),'builder_sha256':sha(builder)}
    result=build_cache(store,ids,a.output,identity,checkpoint_every=100)
    print('Cache terminada:',a.output,'grafos:',result['graphs'],flush=True)
finally:
    store.close()
