"""HotpotQA BF16/vLLM: new protocol, separate from the NF4 pilot."""
import os
os.environ['VLLM_NO_USAGE_STATS']='1'
os.environ['DO_NOT_TRACK']='1'
os.environ['VLLM_WORKER_MULTIPROC_METHOD']='spawn'
os.environ['VLLM_USE_V2_MODEL_RUNNER']='0'
os.environ['VLLM_USE_FLASHINFER_SAMPLER']='0'
import argparse,ast,concurrent.futures,hashlib,importlib.util,json,operator,queue,re,string,sys,time,uuid
from pathlib import Path
engine_path=Path('react_engine.py')
if not engine_path.exists():engine_path=Path('src/widgets/m23/l13/react_engine.py')
spec=importlib.util.spec_from_file_location('react_engine',engine_path)
eng=importlib.util.module_from_spec(spec);sys.modules[spec.name]=eng;spec.loader.exec_module(eng)
MODEL='Qwen/Qwen2.5-1.5B-Instruct'
REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
DATA_REV='1908d6afbbead072334abe2965f91bd2709910ab'
DATA_SHA='e9930d56a776b0cc4ae8e7fcdcbb8392db8ec3b1610d8cec93a6baf5489e5121'

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

def atomic_write(path,content):
    path=Path(path);tmp=path.with_name(path.name+'.tmp-'+uuid.uuid4().hex)
    with tmp.open('xb') as f:f.write(content);f.flush();os.fsync(f.fileno())
    os.replace(tmp,path)

stopwords={'the','a','an','of','in','to','is','are','what','who','which','and','was','for','on','did','does','where'}
words=lambda s:set(re.findall(r'[a-z0-9]+',s.lower()))-stopwords

def context_documents(row):
    return [(title,' '.join(sentences)) for title,sentences in zip(row['context']['title'],row['context']['sentences'])]
def searcher(documents):
    def search(query):
        terms=words(query)
        if not terms:return 'No matching documents.'
        ranked=sorted(enumerate(documents),key=lambda x:(-len(terms & words(x[1][0]))*2-len(terms & words(x[1][1])),x[0]))
        hits=[f'{title}: {body[:700]}' for _,(title,body) in ranked if terms & words(title+' '+body)]
        return '\n'.join(hits[:2]) if hits else 'No matching documents.'
    return search

ops={ast.Add:operator.add,ast.Sub:operator.sub,ast.Mult:operator.mul,ast.Div:operator.truediv}
def calculate(expression):
    def visit(node,depth=0):
        if depth>8:raise ValueError('too deep')
        if isinstance(node,ast.Constant) and type(node.value) in (int,float) and abs(node.value)<1e9:return node.value
        if isinstance(node,ast.BinOp) and type(node.op) in ops:return ops[type(node.op)](visit(node.left,depth+1),visit(node.right,depth+1))
        if isinstance(node,ast.UnaryOp) and isinstance(node.op,ast.USub):return -visit(node.operand,depth+1)
        raise ValueError('unsupported expression')
    result=visit(ast.parse(expression,mode='eval').body)
    if abs(result)>1e12:raise ValueError('result too large')
    return str(result)

def normalize(s):
    s=s.lower();s=''.join(c for c in s if c not in string.punctuation)
    return ' '.join(x for x in s.split() if x not in {'a','an','the'})

def examples(mode):
    if mode=='reason':
        return [{'role':'user','content':'Document: Aster is in Luma. Luma is in Oria. What country is Aster in?'},
                {'role':'assistant','content':'{"thought":"Combine the two facts.","final":"Oria"}'}]
    thought='"thought":"Find the city",' if mode=='react' else ''
    return [{'role':'user','content':'Use search to find the country where Ava works.'},
            {'role':'assistant','content':'{'+thought+'"action":"search","argument":"Ava"}'},
            {'role':'user','content':'Observation: Ava works in Riga.'},
            {'role':'assistant','content':'{"action":"search","argument":"Riga"}'},
            {'role':'user','content':'Observation: Riga is in Latvia.'},
            {'role':'assistant','content':'{"final":"Latvia"}'}]

def actual_messages(messages,mode):
    system=dict(messages[0]);system['content'] += (' Include a brief thought before actions when useful.' if mode=='react' else
        ' Do not include a thought field.' if mode=='act' else ' Use only the supplied documents and return a final answer.')
    return [system]+examples(mode)+messages[1:]
def render(messages,mode):return tok.apply_chat_template(actual_messages(messages,mode),tokenize=False,add_generation_prompt=True)
def count(messages,mode):return len(tok(render(messages,mode),add_special_tokens=False)['input_ids'])

class Batcher:
    def __init__(self): self.q=queue.Queue()
    def policy(self,mode):
        def call(messages,allowance):
            future=concurrent.futures.Future();self.q.put((mode,messages,allowance,future));return future.result()
        return call
    def serve(self,jobs):
        while not all(x.done() for x in jobs) or not self.q.empty():
            try:first=self.q.get(timeout=.1)
            except queue.Empty:continue
            requests=[first];deadline=time.monotonic()+.2
            while len(requests)<8:
                try:requests.append(self.q.get(timeout=max(0,deadline-time.monotonic())))
                except queue.Empty:break
            by_limit={}
            for item in requests:by_limit.setdefault(item[2],[]).append(item)
            for allowance,group in by_limit.items():
                try:
                    prompts=[render(messages,mode) for mode,messages,_,_ in group]
                    inputs=[tok(prompt,add_special_tokens=False)['input_ids'] for prompt in prompts]
                    started=time.perf_counter()
                    outputs=llm.generate([{'prompt_token_ids':x} for x in inputs],
                        SamplingParams(temperature=0,top_p=1,top_k=0,repetition_penalty=1.1,
                                       max_tokens=allowance,stop_token_ids=eos),use_tqdm=False)
                    if len(outputs)!=len(group):raise ValueError('Faltan respuestas')
                    batch={'batch_size':len(group),'max_new_tokens':allowance,'seconds':time.perf_counter()-started,
                           'prompt_sha256':[hashlib.sha256(p.encode('utf8')).hexdigest() for p in prompts],
                           'finish_reasons':[o.outputs[0].finish_reason for o in outputs]}
                    with batchlog.open('a',encoding='utf8') as log:log.write(json.dumps(batch)+'\n');log.flush()
                    for i,(_,_,_,future) in enumerate(group):
                        result=outputs[i]
                        if list(result.prompt_token_ids)!=inputs[i] or len(result.outputs)!=1:raise ValueError('Tokens o salida inesperados')
                        item=result.outputs[0]
                        if item.finish_reason not in ('stop','length'):raise ValueError('Parada inesperada')
                        future.set_result(eng.PolicyResponse(item.text,len(inputs[i]),len(item.token_ids),prompts[i]))
                except Exception as exc:
                    print('Error del adaptador:',type(exc).__name__,str(exc)[:500],flush=True)
                    for _,_,_,future in group:
                        if not future.done():future.set_exception(exc)

def run_case(i,mode,batcher):
    row=data[i];documents=context_documents(row)
    if mode=='reason':
        snippet='\n'.join(title+': '+body[:160] for title,body in documents)
        question='Documents (truncated):\n'+snippet+'\nQuestion: '+row['question']+'\nGive the final answer.'
        tools={}
    else:
        question=row['question']+' Use search or calculate when useful, then return the final answer.'
        tools={'search':searcher(documents),'calculate':calculate}
    result=eng.run_agent(question,batcher.policy(mode),tools,lambda x:count(x,mode),
        max_steps=6,max_total_tokens=4096,max_context_tokens=2048,max_new_tokens=64,timeout_seconds=3600,repeat_limit=2,
        allow_thought=(mode!='act'))
    answer=result['answer'] or ''
    return {'index':i,'id':row['id'],'mode':mode,'question':row['question'],'reference':row['answer'],
            'answer':answer,'correct':normalize(answer)==normalize(row['answer']),
            'tokens_used':result['tokens_used'],'stop_reason':result['stop_reason'],'events':result['events']}

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--model-path',required=True);ap.add_argument('--records',required=True)
    ap.add_argument('--output',required=True);ap.add_argument('--limit',type=int,default=200)
    ap.add_argument('--eager',action='store_true')
    args=ap.parse_args()
    if Path(args.model_path).name!=REV:ap.error('Snapshot de otra revisión')
    if not 1<=args.limit<=200:ap.error('Límite fuera de rango')
    global data,tok,llm,batchlog,SamplingParams,eos
    import torch,transformers,vllm
    from transformers import AutoTokenizer,GenerationConfig
    from vllm import LLM,SamplingParams
    if not torch.cuda.is_available():raise RuntimeError('Se requiere CUDA')
    source=Path(args.model_path)
    if digest(args.records)!=DATA_SHA:raise ValueError('Datos HotpotQA distintos de la revisión fijada')
    data=json.loads(Path(args.records).read_text(encoding='utf8'))
    if len(data)!=200:raise ValueError('Faltan preguntas')
    names=['config.json','generation_config.json','tokenizer_config.json','tokenizer.json','merges.txt','vocab.json','model.safetensors']
    hashes={name:digest(source/name) for name in names}
    eos=GenerationConfig.from_pretrained(source,local_files_only=True).eos_token_id
    eos=sorted(eos if isinstance(eos,list) else [eos])
    protocol={'model':MODEL,'revision':REV,'data_revision':DATA_REV,'data_sha256':DATA_SHA,
        'model_sha256':hashes,'code_sha256':digest(__file__),'engine_sha256':digest(eng.__file__),
        'torch':torch.__version__,'transformers':transformers.__version__,
        'vllm':vllm.__version__,'cuda_version':torch.version.cuda,'gpu':torch.cuda.get_device_name(),
        'capability':list(torch.cuda.get_device_capability()),'backend':'vllm','dtype':'bfloat16',
        'limit':args.limit,'batch_problems':8,'modes':['reason','act','react'],'max_steps':6,
        'max_total_tokens':4096,'max_context_tokens':2048,'max_new_tokens':64,
        'repetition_penalty':1.1,'decoding':'greedy','eos':eos,'max_model_len':2048,
        'max_num_seqs':16,'max_num_batched_tokens':2048,'gpu_memory_utilization':.55,
        'enable_prefix_caching':True,'async_scheduling':False,'enforce_eager':args.eager,
        'engine_seed':2026,'vllm_use_v2_model_runner':'0','vllm_use_flashinfer_sampler':'0'}
    path=Path(args.output);meta=path.with_suffix(path.suffix+'.protocol.json');parts=path.with_suffix(path.suffix+'.parts')
    batchlog=path.with_suffix(path.suffix+'.batches.jsonl')
    if (path.exists() or parts.exists()) and not meta.exists():raise ValueError('Archivo sin manifiesto')
    if meta.exists():
        if json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo distinto')
    else:atomic_write(meta,json.dumps(protocol,ensure_ascii=False,indent=2).encode('utf8'))
    parts.mkdir(exist_ok=True);old={}
    for f in sorted(parts.glob('case-*.json')):
        row=json.loads(f.read_text(encoding='utf8'));i=row['index'];mode=row['mode'];key=(i,mode)
        if f.name!=f'case-{mode}-{i:04}.json' or not 0<=i<args.limit or mode not in protocol['modes'] or key in old:
            raise ValueError('Checkpoint duplicado o inesperado')
        if (row['id']!=data[i]['id'] or row['question']!=data[i]['question'] or row['reference']!=data[i]['answer']
            or row['correct']!=(normalize(row['answer'])==normalize(row['reference']))
            or row['tokens_used']!=sum(e.get('input_tokens',0)+e.get('output_tokens',0) for e in row['events'])
            or (row['stop_reason']=='final' and (not row['events'] or row['events'][-1].get('final')!=row['answer']))
            or (row['stop_reason']!='final' and row['answer']!='')):
            raise ValueError('Checkpoint incoherente')
        old[key]=row
    if path.exists() and len(old)!=args.limit*3:raise ValueError('Resultado final sin checkpoints completos')
    tok=AutoTokenizer.from_pretrained(source,local_files_only=True)
    llm=LLM(model=str(source),tokenizer=str(source),dtype='bfloat16',max_model_len=2048,
        gpu_memory_utilization=.55,max_num_seqs=16,max_num_batched_tokens=2048,
        enable_prefix_caching=True,enforce_eager=args.eager,seed=2026,async_scheduling=False)
    for mode in protocol['modes']:
        for start in range(0,args.limit,8):
            indices=list(range(start,min(start+8,args.limit)))
            if all((i,mode) in old for i in indices):continue
            batcher=Batcher()
            with concurrent.futures.ThreadPoolExecutor(max_workers=len(indices)) as pool:
                jobs=[pool.submit(run_case,i,mode,batcher) for i in indices]
                batcher.serve(jobs);rows=[j.result() for j in jobs]
            if any(row['stop_reason']=='policy_error' for row in rows):
                raise RuntimeError('Error del adaptador de modelo; no se cuenta como fallo del agente')
            for row in rows:
                key=(row['index'],mode)
                if key in old and old[key]!=row:raise ValueError('Lote parcial divergente; no se modifica')
            for row in rows:
                key=(row['index'],mode)
                if key not in old:
                    atomic_write(parts/f'case-{mode}-{row["index"]:04}.json',json.dumps(row,ensure_ascii=False).encode('utf8'));old[key]=row
            print(mode,'completados',min(start+8,args.limit),'de',args.limit,flush=True)
    payload=''.join(json.dumps(old[(i,mode)],ensure_ascii=False)+'\n' for mode in protocol['modes'] for i in range(args.limit)).encode('utf8')
    if path.exists():
        if digest(path)!=hashlib.sha256(payload).hexdigest():raise ValueError('Resultado ensamblado divergente')
    else:atomic_write(path,payload)
    print('HotpotQA completo',args.limit*3,'filas',flush=True)

if __name__=='__main__':main()
