"""Mismos problemas para Qwen 7B Q4_K_M, mediante llama.cpp y shards GGUF.

Ejecutar con llama-cuda; la implementación de muestreo y la plantilla son
las de llama.cpp y no se presuponen idénticas bit a bit al backend HF.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import time
import llama_cpp
import answer_extract_v2 as extractor

REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'

def digest(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
    return h.hexdigest()

def save(path,payload):
    tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(payload,ensure_ascii=False),encoding='utf8');tmp.replace(path)

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--model-path',required=True,help='Primer shard GGUF')
    ap.add_argument('--samples',required=True);ap.add_argument('--output',required=True)
    ap.add_argument('--count',type=int,default=200);ap.add_argument('--n',type=int,default=16);args=ap.parse_args()
    first=Path(args.model_path);second=first.with_name(first.name.replace('00001-of-00002','00002-of-00002'))
    if first.parent.name!=REV or first==second or not first.exists() or not second.exists():ap.error('Se requieren ambos shards de la revisión fijada')
    if not 1<=args.count<=200 or args.n<1:ap.error('Cantidad inválida')
    if not llama_cpp.llama_supports_gpu_offload():raise RuntimeError('llama.cpp no dispone de backend GPU')
    with gzip.open(args.samples,'rt',encoding='utf8') as f:old=[json.loads(line) for line in f if line.strip()]
    rows=sorted((r for r in old if r['problema']<args.count and r['muestra']==0),key=lambda r:r['problema'])
    if [r['problema'] for r in rows]!=list(range(args.count)):raise ValueError('Preguntas incompletas')
    out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
    meta={'revision':REV,'weights_sha256':{first.name:digest(first),second.name:digest(second)},
          'questions_sha256':digest(args.samples),'extractor_sha256':digest(extractor.__file__),'code_sha256':digest(__file__),
          'count':args.count,'n':args.n,'seed_rule':'630000 + 1000*problem + sample',
          'temperature':.8,'top_p':.9,'top_k':0,'min_p':0.,'repeat_penalty':1.1,'last_n_tokens_size':1024,
          'max_tokens':256,'backend':'llama_cpp','llama_cpp':llama_cpp.__version__,'gpu_layers':-1,'context':1024,
          'note':'Q4_K_M; tiempos de pared sincronizados por llamada, implementación y plantilla pueden diferir de HF.'}
    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)
    model=llama_cpp.Llama(model_path=str(first),n_gpu_layers=-1,n_ctx=1024,last_n_tokens_size=1024,verbose=True)
    parameters=model._model.n_params()
    for row in rows:
        i=row['problema'];file=out/f'problem-{i:04d}.json'
        if file.exists():
            saved=json.loads(file.read_text(encoding='utf8'))
            if saved['question']!=row['pregunta'] or len(saved['samples'])!=args.n:raise ValueError('Checkpoint incompatible')
            continue
        prompt='Solve step by step. '+row['pregunta']+'\nGive the final numerical answer on its own line as #### followed by the number.'
        generated=[]
        for sample in range(args.n):
            start=time.perf_counter()
            response=model.create_chat_completion(messages=[{'role':'user','content':prompt}],max_tokens=256,
                temperature=.8,top_p=.9,top_k=0,min_p=0.,repeat_penalty=1.1,seed=630000+1000*i+sample)
            elapsed=time.perf_counter()-start;choice=response['choices'][0]
            text=choice['message']['content'] or '';truncated=choice['finish_reason']=='length'
            answer=extractor.extract(text,truncated=truncated);usage=response['usage']
            generated.append({'text':text,'answer':answer,'correct':None if answer is None else int(answer==row['referencia']),
                'input_tokens':usage['prompt_tokens'],'output_tokens':usage['completion_tokens'],
                'truncated':truncated,'seconds':elapsed})
        save(file,{'problem':i,'question':row['pregunta'],'reference':row['referencia'],'parameters':parameters,'samples':generated})
        print('problema',i,'muestras',len(generated),flush=True)
    model.close()

if __name__=='__main__':main()
