"""Reanaliza respuestas reales Qwen 1.5B de l03 sin volver a generar.

El archivo conserva el tiempo medido del lote de 32, que incluye puntuación
de logits. Las primeras diez sirven para FLOPs; el tiempo solo es medido
para el lote completo, no se prorratea para atribuirlo a esas diez.
"""
import argparse,gzip,hashlib,json,math,os,sys
from pathlib import Path
from safetensors import safe_open
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'l05'))
import answer_extract_v2 as extractor

REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
UNCOMPRESSED_SHA='8abb79c6265c9dca427004acdd7958ee02b54f0ef9454d05c2e04d224606d003'
def sha(path):
 h=hashlib.sha256()
 with Path(path).open('rb') as f:
  for x in iter(lambda:f.read(1024*1024),b''):h.update(x)
 return h.hexdigest()
def save(path,obj):
 tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(obj,ensure_ascii=False),encoding='utf8');os.replace(tmp,path)
def main():
 p=argparse.ArgumentParser();p.add_argument('--model-path',required=True);p.add_argument('--samples',required=True)
 p.add_argument('--output',required=True);a=p.parse_args();model=Path(a.model_path);data=Path(a.samples);out=Path(a.output)
 if model.name!=REV:raise ValueError('Revisión incorrecta')
 raw=gzip.decompress(data.read_bytes())
 if hashlib.sha256(raw).hexdigest()!=UNCOMPRESSED_SHA:raise ValueError('El corpus no coincide con l03')
 records=[json.loads(line) for line in raw.decode('utf8').splitlines() if line.strip()]
 if len(records)!=200*64:raise ValueError('Corpus incompleto')
 with safe_open(model/'model.safetensors',framework='pt',device='cpu') as f:
  params=sum(math.prod(f.get_slice(key).get_shape()) for key in f.keys())
 out.mkdir(parents=True,exist_ok=True)
 meta={'revision':REV,'weights_sha256':sha(model/'model.safetensors'),'questions_sha256':sha(data),
       'uncompressed_sha256':UNCOMPRESSED_SHA,'extractor_sha256':sha(extractor.__file__),
       'code_sha256':sha(__file__),'count':200,'n':32,'compute_grid_n':10,
       'backend':'transformers_l03','source_samples':64,'original_batch_size':32,
       'seed_rule':'lote: problem*64 + first sample','temperature':.8,'top_p':.9,'top_k':0,
       'repetition_penalty':1.1,'max_tokens':256,
       'seconds_definition':'Tiempo real del lote completo de 32, incluida puntuación de logits; no se prorratea.'}
 manifest=out/'protocol.json'
 if manifest.exists() and json.loads(manifest.read_text(encoding='utf8'))!=meta:raise ValueError('Protocolo diferente')
 if not manifest.exists():save(manifest,meta)
 for i in range(200):
  group=[r for r in records if r['problema']==i and r['muestra']<32]
  group.sort(key=lambda r:r['muestra'])
  if [r['muestra'] for r in group]!=list(range(32)) or any(r['lote']!=32 or r['semilla_lote']!=64*i for r in group):
   raise ValueError(f'Lote inválido para {i}')
  if any(not 0<r['tokens_salida']<=256 or not r['tokens_entrada']>0 or
         (r['truncada'] and r['tokens_salida']!=256) for r in group):
   raise ValueError('Conteos o truncamiento incompatibles con el máximo 256')
  if len({r['pregunta'] for r in group})!=1 or len({r['referencia'] for r in group})!=1:
   raise ValueError('Problema o referencia incoherentes')
  if len({r['tokens_entrada'] for r in group})!=1:raise ValueError('El prompt cambia dentro del lote')
  times={r['segundos_lote_generacion_y_puntuacion'] for r in group}
  if len(times)!=1:raise ValueError('Tiempo de lote incoherente')
  converted=[]
  for row in group:
   answer=extractor.extract(row['texto'],truncated=row['truncada'])
   converted.append({'text':row['texto'],'answer':answer,'correct':None if answer is None else int(answer==row['referencia']),
                     'input_tokens':row['tokens_entrada'],'output_tokens':row['tokens_salida'],'truncated':row['truncada'],
                     'seconds':None,'batch_index':0,'batch_size':32,'batch_wall_seconds':next(iter(times))})
  payload={'problem':i,'question':group[0]['pregunta'],'reference':group[0]['referencia'],
           'parameters':params,'samples':converted}
  target=out/f'problem-{i:04d}.json'
  if target.exists() and json.loads(target.read_text(encoding='utf8'))!=payload:
   raise ValueError('Archivo previo incompatible')
  if not target.exists():save(target,payload)
 print('reanalizadas',200,'preguntas y',200*32,'respuestas reales; k=10 para coste, k=32 para tiempo medido')

if __name__=='__main__':main()
