"""Extrae CLS de CodeBERT congelado; no ejecuta las funciones C del corpus."""
import argparse, hashlib, json, os
from pathlib import Path
import numpy as np
import torch
import transformers
from transformers import AutoModel, AutoTokenizer

p=argparse.ArgumentParser(); p.add_argument('--root',type=Path,required=True); p.add_argument('--model',type=Path,required=True)
p.add_argument('--output',type=Path,default=Path('codebert-cls.npy')); p.add_argument('--batch-size',type=int,default=16); p.add_argument('--resume',action='store_true')
p.add_argument('--device',choices=['auto','cpu','cuda'],default='auto'); p.add_argument('--threads',type=int,default=4)
a=p.parse_args()
if min(a.batch_size,a.threads)<1:p.error('El tamaño de lote y los hilos deben ser positivos')
files=[a.root/f'primevul_{s}.jsonl' for s in ('train','valid','test')]
hashes={}
for file in files:
    with file.open('rb') as f: hashes[file.name]=hashlib.file_digest(f,'sha256').hexdigest()
model_hashes={}
for name in ('config.json','pytorch_model.bin','vocab.json','merges.txt','tokenizer_config.json','special_tokens_map.json'):
    with (a.model/name).open('rb') as f: model_hashes[name]=hashlib.file_digest(f,'sha256').hexdigest()
for name in ('tokenizer.json','added_tokens.json'):
    if (a.model/name).is_file():
        with (a.model/name).open('rb') as f: model_hashes[name]=hashlib.file_digest(f,'sha256').hexdigest()
rows=[]
for file in files:
    with file.open(encoding='utf-8') as f:
        for line in f: rows.append(json.loads(line)['func'])
device=torch.device(('cuda' if torch.cuda.is_available() else 'cpu') if a.device=='auto' else a.device); torch.set_num_threads(a.threads)
if device.type=='cuda' and not torch.cuda.is_available():p.error('CUDA no está disponible')
tokenizer=AutoTokenizer.from_pretrained(a.model,local_files_only=True)
model=AutoModel.from_pretrained(a.model,local_files_only=True,use_safetensors=False).to(device).eval()
for p0 in model.parameters(): p0.requires_grad_(False)
hidden=model.config.hidden_size; meta=a.output.with_suffix('.meta.json');mask_path=a.output.with_suffix('.trunc.npy'); start=0; truncated=0
identity={'sources':hashes,'model':model_hashes,'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'rows':len(rows),'hidden':hidden,'max_length':512,'representation':'last_hidden_state CLS float32','torch':str(torch.__version__),'transformers':transformers.__version__,'device':str(device),'threads':a.threads,'format_version':2}
if a.resume:
    saved=json.loads(meta.read_text(encoding='utf-8'))
    if saved['identity']!=identity:raise ValueError('El archivo no corresponde al corpus o modelo actual')
    start=saved['completed']; truncated=saved['truncated']; array=np.lib.format.open_memmap(a.output,mode='r+')
    if array.shape!=(len(rows),hidden) or array.dtype!=np.float32:raise ValueError('Dimensiones incompatibles')
    truncated_mask=np.lib.format.open_memmap(mask_path,mode='r+')
    if truncated_mask.shape!=(len(rows),) or truncated_mask.dtype!=np.bool_:raise ValueError('Máscara de truncamiento incompatible')
else:
    a.output.parent.mkdir(parents=True,exist_ok=True)
    array=np.lib.format.open_memmap(a.output,mode='w+',dtype=np.float32,shape=(len(rows),hidden))
    truncated_mask=np.lib.format.open_memmap(mask_path,mode='w+',dtype=np.bool_,shape=(len(rows),));truncated_mask[:]=False;truncated_mask.flush()
def save(completed):
    temp=meta.with_name(meta.name+'.tmp');temp.write_text(json.dumps({'identity':identity,'completed':completed,'truncated':truncated},indent=2),encoding='utf-8');os.replace(temp,meta)
if not a.resume: save(0)
with torch.no_grad():
    for begin in range(start,len(rows),a.batch_size):
        group=rows[begin:begin+a.batch_size]
        # Se cuenta el truncamiento sin ocultar el número de tokens original.
        lengths=tokenizer(group,add_special_tokens=True,truncation=False,return_length=True)['length']
        flags=np.asarray([length>512 for length in lengths],dtype=np.bool_);truncated+=int(flags.sum())
        inputs=tokenizer(group,return_tensors='pt',padding=True,truncation=True,max_length=512)
        inputs={k:v.to(device) for k,v in inputs.items()}
        vectors=model(**inputs).last_hidden_state[:,0,:].float().cpu().numpy()
        array[begin:begin+len(group)]=vectors;truncated_mask[begin:begin+len(group)]=flags;array.flush();truncated_mask.flush();save(begin+len(group))
        if (begin//a.batch_size)%100==0: print('procesadas',begin+len(group),'/',len(rows),'truncadas',truncated,flush=True)
print('vectores',a.output,'truncadas',truncated,'de',len(rows),flush=True)
