"""Qwen2.5-7B Q4 mediante servidor llama.cpp compartido y checkpoints por problema.

Cada llamada es secuencial, por lo que su tiempo de pared es medido, no
prorrateado. El servidor es externo a este proceso y no se arranca ni detiene.
"""
import argparse,gzip,hashlib,json,os,re,sys,time
from pathlib import Path
from urllib.request import Request,ProxyHandler,HTTPRedirectHandler,build_opener

sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'l05'))
import answer_extract_v2 as extractor
MODEL='qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf'
REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
SHAS=('dfce12e3862a5283ccfb88221b48480e58745165de856439950d0f22590580db',
      '539cf93f78e887edea1c04e2d7d8cdaca9d01dae9c9025bcb8accbe29df3d72a')
PARAMETERS=7615616512
class NoRedirect(HTTPRedirectHandler):
 def redirect_request(self,*args,**kwargs):raise RuntimeError('Redirección no permitida')
def sha(path):
 h=hashlib.sha256()
 with Path(path).open('rb') as f:
  for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
 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('--server-log',required=True);p.add_argument('--output',required=True)
 p.add_argument('--port',type=int,default=11441);p.add_argument('--count',type=int,default=200)
 p.add_argument('--n',type=int,default=2);p.add_argument('--batch-rows',type=int,default=5);a=p.parse_args()
 first=Path(a.model_path);second=first.with_name(first.name.replace('00001-of-00002','00002-of-00002'))
 if first.name!=MODEL or first.parent.name!=REV or not second.exists() or not 1<=a.count<=200 or a.n<1 or a.batch_rows<1:
  raise ValueError('Modelo o parámetros inválidos')
 if (sha(first),sha(second))!=SHAS:raise ValueError('Hashes del modelo incompatibles')
 log=Path(a.server_log).read_text(encoding='utf8',errors='replace')
 if not re.search(r'offloaded\s+29/29\s+layers\s+to\s+GPU',log,re.I) or MODEL not in log:
  raise ValueError('El log no acredita el modelo y las 29 capas en GPU')
 questions=Path(a.samples)
 with gzip.open(questions,'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']<a.count and r['muestra']==0),key=lambda r:r['problema'])
 if [r['problema'] for r in rows]!=list(range(a.count)):raise ValueError('Preguntas incompletas')
 out=Path(a.output);out.mkdir(parents=True,exist_ok=True)
 meta={'revision':REV,'model':MODEL,'weights_sha256':dict(zip((first.name,second.name),SHAS)),
       'questions_sha256':sha(questions),'extractor_sha256':sha(extractor.__file__),'code_sha256':sha(__file__),
       'count':a.count,'n':a.n,'seed_rule':'630000 + 1000*problem + sample','temperature':.8,'top_p':.9,
       'top_k':0,'min_p':0.,'repeat_penalty':1.1,'repeat_last_n':-1,'max_tokens':256,
       'backend':'llama-server','server_version':'b9354-9777256c3','device':'CUDA',
       'offloaded_layers':'29/29 verificado en log por sesión',
       'seconds_definition':'Tiempo de pared de cada petición secuencial; incluye HTTP y contención.',
       'note':'Q4_K_M; sampling, plantillas, caché y hardware difieren de Transformers y vLLM.'}
 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)
 opener=build_opener(ProxyHandler({}),NoRedirect());endpoint=f'http://127.0.0.1:{a.port}/v1/chat/completions'
 completed=0
 for row in rows:
  i=row['problema'];file=out/f'problem-{i:04d}.json'
  if file.exists():
   previous=json.loads(file.read_text(encoding='utf8'))
   if previous['problem']!=i or previous['question']!=row['pregunta'] or len(previous['samples'])!=a.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.'
  samples=[]
  for j in range(a.n):
   seed=630000+1000*i+j
   request={'model':MODEL,'messages':[{'role':'user','content':prompt}],'max_tokens':256,
            'temperature':.8,'top_p':.9,'top_k':0,'min_p':0.,'repeat_penalty':1.1,
            'repeat_last_n':-1,'seed':seed,'verbose':True}
   req=Request(endpoint,data=json.dumps(request).encode('utf8'),headers={'Content-Type':'application/json'})
   start=time.perf_counter()
   with opener.open(req,timeout=900) as response:result=json.load(response)
   elapsed=time.perf_counter()-start
   if result.get('model')!=MODEL or result.get('system_fingerprint')!='b9354-9777256c3':
    raise ValueError('Servidor o modelo distintos')
   details=result.get('__verbose',{}).get('generation_settings',{})
   if (details.get('seed')!=seed or abs(details.get('temperature',-1)-.8)>1e-5
       or abs(details.get('top_p',-1)-.9)>1e-5 or details.get('top_k')!=0
       or abs(details.get('min_p',-1))>1e-8 or abs(details.get('repeat_penalty',-1)-1.1)>1e-5):
    raise ValueError(f'Parámetros efectivos del servidor no coinciden: {details}')
   choice=result['choices'][0];text=choice['message']['content'] or ''
   truncated=choice['finish_reason']=='length';answer=extractor.extract(text,truncated=truncated);usage=result['usage']
   expected_prompt=('<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n'
                    '<|im_start|>user\n'+prompt+'<|im_end|>\n<|im_start|>assistant\n')
   if result['__verbose'].get('prompt')!=expected_prompt:raise ValueError(f'Plantilla diferente: {result["__verbose"].get("prompt")!r}')
   if details.get('repeat_last_n',0)<usage['prompt_tokens']+256:raise ValueError(f'Penalización con contexto insuficiente: {details.get("repeat_last_n")}')
   samples.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'],
                   'cached_tokens':usage.get('prompt_tokens_details',{}).get('cached_tokens',0),
                   'repeat_last_n_effective':details['repeat_last_n'],
                   'truncated':truncated,'seconds':elapsed,'batch_index':j,'batch_size':1,'batch_wall_seconds':elapsed})
  save(file,{'problem':i,'question':row['pregunta'],'reference':row['referencia'],'parameters':PARAMETERS,'samples':samples})
  completed+=1;print('problema',i,'muestras',len(samples),flush=True)
  if completed>=a.batch_rows:
   print('lote de problemas completo; servidor queda disponible',flush=True);return

if __name__=='__main__':main()
