"""Comparación pareada CoT/PAL en GSM8K y una variante numérica derivada.

El modelo corre en el host; el código propuesto corre exclusivamente en el
sandbox de l14 en Ubuntu. La variante añade un producto exacto al resultado.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
from decimal import Decimal, InvalidOperation, localcontext
import hashlib
import json
import os
from pathlib import Path
import random
import re
import subprocess
import time
from pure_python import check_pure
from model_integrity import verify as verify_manifest
from urllib.request import Request, ProxyHandler, HTTPRedirectHandler, build_opener

REV = '740312add88f781978c0658806c59bc2815b9866'
LARGE_FACTOR = 1000000007


def numeric(text):
    cleaned=text.strip().replace(',','').replace('$','')
    try:
        result=Decimal(cleaned)
        return result if result.is_finite() else None
    except InvalidOperation: return None


def final_number(text):
    found=re.findall(r'(?im)^\s*FINAL\s*:\s*([^\n]+)', text)
    return numeric(found[-1]) if found else None


def extract_code(text):
    found=re.search(r'```(?:python)?\s*\n(.*?)```',text,re.S | re.I)
    code=(found.group(1) if found else text).strip()
    if not code or len(code)>10000: raise ValueError('programa vacío o demasiado largo')
    return code


def synthetic(n, seed=1414):
    rng=random.Random(seed)
    rows=[]
    for index in range(n):
        a=rng.randint(10**7,10**9); b=rng.randint(10**6,min(10**8,a))
        if index%2:
            question=f'Una colección tenía {a} fichas y perdió {b}. ¿Cuántas quedan?'
            answer=a-b
        else:
            question=f'Un archivo contiene {a} registros y otro {b}. ¿Cuántos registros suman?'
            answer=a+b
        rows.append({'id':f'large-{index}', 'question':question, 'answer':str(answer), 'family':'synthetic-large'})
    return rows


def large_variant(row):
    answer=numeric(row['answer'])
    if answer is None:raise ValueError('invalid original answer')
    with localcontext() as ctx:
        ctx.prec=max(64,len(answer.as_tuple().digits)+24)
        transformed=answer*LARGE_FACTOR
    return {'id':row['id']+'-large','source_id':row['id'],'family':'gsm8k-large',
            'question':row['question']+'\nAfter solving the original problem, multiply its numeric answer by '+str(LARGE_FACTOR)+'. Return that product as the final answer.',
            'answer':str(transformed),'factor':LARGE_FACTOR}


def task_rows(n):
    from datasets import load_dataset
    data=load_dataset('openai/gsm8k','main',revision=REV,split='test')
    ids=list(range(len(data))); random.Random(1414).shuffle(ids)
    rows=[]
    for i in ids[:n]:
        row=data[i]; answer=row['answer'].split('####')[-1].strip()
        if numeric(answer) is None: raise ValueError('respuesta GSM8K no numérica')
        rows.append({'id':f'gsm8k-{i}', 'question':row['question'], 'answer':answer,'family':'gsm8k'})
    return rows+[large_variant(row) for row in rows]


def prompt_for(row,method):
    instruction=('Solve the problem step by step, then put the number alone on a final line FINAL: <number>.'
        if method=='cot' else 'Write only Python code that solves the problem and prints exactly FINAL: <number>.')
    return instruction+'\n'+row['question']


def paired_prefetch(generate,rows,destination,max_new=None):
    """Solicita de dos en dos, pero entrega y registra resultados en orden fijo."""
    path=Path(destination)
    completed=len(path.read_bytes().splitlines())-1 if path.exists() and path.stat().st_size else 0
    pending_prompts=[prompt_for(row,method) for row in rows for method in ('cot','pal')][completed:]
    if max_new is not None:pending_prompts=pending_prompts[:max_new]
    position=0;queued=[]
    def next_result(prompt):
        nonlocal position,queued
        if not queued:
            batch=pending_prompts[position:position+2]
            if not batch or batch[0]!=prompt:raise ValueError('orden de solicitud inesperado')
            with ThreadPoolExecutor(max_workers=2) as executor:
                results=list(executor.map(generate,batch))
            queued=list(zip(batch,results));position+=len(batch)
        expected,result=queued.pop(0)
        if prompt!=expected:raise ValueError('orden de respuesta inesperado')
        return result
    return next_result


def run(generate, evaluate, rows, destination, metadata, max_new=None):
    if max_new is not None and max_new<1:raise ValueError('max_new debe ser positivo')
    path=Path(destination); completed=set()
    if path.exists() and path.stat().st_size:
        raw=path.read_bytes()
        if not raw.endswith(b'\n'):
            raise ValueError('JSONL incompleto: conservar copia e investigar la última línea antes de reanudar')
        lines=raw.decode('utf-8').splitlines()
        if json.loads(lines[0]) != {'metadata':metadata}: raise ValueError('metadatos diferentes')
        expected=[(row,method) for row in rows for method in ('cot','pal')]
        if len(lines)-1>len(expected):raise ValueError('más filas que el corpus')
        for index,line in enumerate(lines[1:]):
            record=json.loads(line); key=(record['id'],record['method'])
            if key in completed: raise ValueError('resultado duplicado')
            original,method=expected[index]
            if record['method']!=method or any(record.get(k)!=v for k,v in original.items()):
                raise ValueError('prefijo de corpus diferente o fuera de orden')
            if type(record.get('correct')) is not bool or not isinstance(record.get('usage'),dict):
                raise ValueError('fila previa inválida')
            completed.add(key)
    written=0
    with path.open('a',encoding='utf-8') as out:
        def persist(record):
            out.write(json.dumps(record,ensure_ascii=False)+'\n'); out.flush(); os.fsync(out.fileno())
        if path.stat().st_size==0:
            persist({'metadata':metadata})
        for row in rows:
            for method in ('cot','pal'):
                if (row['id'],method) in completed: continue
                text,usage=generate(prompt_for(row,method))
                if any(type(usage.get(k)) is not int or usage[k]<0 for k in ('prompt_tokens','completion_tokens')):
                    raise RuntimeError('model token usage missing or invalid')
                if usage['completion_tokens']>metadata['max_tokens']:
                    raise RuntimeError('model exceeded completion token ceiling')
                error=None; observation=None
                if method=='cot': value=final_number(text)
                else:
                    try:
                        code=extract_code(text)
                        allowed,reason=check_pure(code)
                        if not allowed:
                            status='invalid_code' if reason.startswith('syntax: ') else 'rejected'
                            error=status+': '+reason; value=None
                            observation={'status':status,'reason':reason}
                        else:
                            observation=evaluate(code)
                        if not allowed:
                            record={**row,'method':method,'model_output':text,'usage':usage,
                                    'observation':observation,'parsed':None,'correct':False,'error':error}
                            persist(record)
                            print(row['id'],method,status,reason,flush=True)
                            written+=1
                            if max_new is not None and written>=max_new:return
                            continue
                        if observation.get('status') != 'ok':
                            raise RuntimeError('sandbox inconclusive: '+str(observation.get('status')))
                        try: action=observation['result']['actions'][0]
                        except (KeyError,IndexError,TypeError) as exc: raise RuntimeError('sandbox protocol invalid') from exc
                        if action.get('status') not in ('ok','error') or not isinstance(action.get('output'),str):
                            raise RuntimeError('sandbox action invalid')
                        if action.get('truncated'):
                            raise RuntimeError('sandbox inconclusive: output was truncated')
                        if action['status']!='ok': error=action['output']; value=None
                        else: value=final_number(action['output'])
                    except ValueError as exc: error=str(exc); value=None
                correct=value is not None and value == numeric(row['answer'])
                record={**row,'method':method,'model_output':text,'usage':usage,
                        'observation':observation,'parsed':str(value) if value is not None else None,
                        'correct':correct,'error':error}
                persist(record)
                print(row['id'],method,correct,flush=True)
                written+=1
                if max_new is not None and written>=max_new:return


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--model',required=True); parser.add_argument('--output',required=True)
    parser.add_argument('--n',type=int,default=500)
    parser.add_argument('--server-port',type=int,help='Reutiliza servidor llama.cpp en localhost')
    parser.add_argument('--server-version',default='no especificada')
    parser.add_argument('--max-new',type=int,help='pausa tras este número de filas nuevas completas')
    parser.add_argument('--verified-model-manifest',help='manifiesto SHA de fragmentos creado previamente')
    parser.add_argument('--concurrency',type=int,choices=(1,2),default=1)
    parser.add_argument('--context-per-slot',type=int,choices=(4096,8192),default=8192)
    args=parser.parse_args()
    if not 1<=args.n<=1319: raise ValueError('n debe estar entre 1 y 1319')
    if (args.concurrency,args.context_per_slot) not in ((1,8192),(2,4096)):
        raise ValueError('use un slot de 8192 o dos slots de 4096')
    if args.concurrency==2 and not args.server_port:
        raise ValueError('dos solicitudes exigen servidor verificado')
    files=[]; model_path=Path(args.model)
    split=re.match(r'^(.*)-(\d{5})-of-(\d{5})\.gguf$',model_path.name)
    if split:
        stem,index,total=split.groups()
        if int(index)!=1: raise ValueError('pasar primer fragmento')
        files=[model_path.with_name(f'{stem}-{i:05d}-of-{int(total):05d}.gguf') for i in range(1,int(total)+1)]
    else: files=[model_path]
    hashes={}
    if args.verified_model_manifest:
        hashes=verify_manifest(files,args.verified_model_manifest)
    else:
        for file in files:
            h=hashlib.sha256()
            with file.open('rb') as stream:
                for block in iter(lambda:stream.read(1024*1024),b''): h.update(block)
            hashes[file.name]=h.hexdigest()
    if args.server_port:
        class NoRedirect(HTTPRedirectHandler):
            def redirect_request(self,*a,**k): raise RuntimeError('redirección no permitida')
        def generate(prompt):
            payload={'model':model_path.name,'messages':[{'role':'user','content':prompt}],'temperature':0,'seed':1414,'max_tokens':512}
            request=Request(f'http://127.0.0.1:{args.server_port}/v1/chat/completions',
                            data=json.dumps(payload).encode(),headers={'Content-Type':'application/json'})
            started=time.monotonic()
            with build_opener(ProxyHandler({}),NoRedirect()).open(request,timeout=900) as response: result=json.load(response)
            if result.get('model')!=model_path.name: raise ValueError('modelo distinto en servidor')
            if result.get('system_fingerprint')!='b9354-9777256c3':raise ValueError('backend distinto en servidor')
            usage=dict(result.get('usage',{}));usage['wall_seconds']=time.monotonic()-started
            usage['finish_reason']=result['choices'][0].get('finish_reason')
            return result['choices'][0]['message'].get('content') or '',usage
        runtime='llama.cpp server '+args.server_version
    else:
        import llama_cpp
        model=llama_cpp.Llama(model_path=str(model_path), n_ctx=2048, n_gpu_layers=0, verbose=False)
        def generate(prompt):
            started=time.monotonic()
            response=model.create_chat_completion(messages=[{'role':'user','content':prompt}],temperature=0,seed=1414,max_tokens=512)
            usage=dict(response.get('usage',{}));usage['wall_seconds']=time.monotonic()-started
            usage['finish_reason']=response['choices'][0].get('finish_reason')
            return response['choices'][0]['message']['content'],usage
        runtime='llama_cpp '+llama_cpp.__version__
    if Path('/proc/version').exists():
        from sandbox import run_sandboxed
        evaluate=lambda code:run_sandboxed(code,timeout=30)
    else:
        path=subprocess.check_output(['wsl','-d','Ubuntu','--','wslpath','-a',str(Path(__file__).with_name('sandbox_cli.py').resolve())],text=True).strip()
        def evaluate(code):
            proc=subprocess.run(['wsl','-d','Ubuntu','--','python3',path],input=json.dumps({'code':code}),capture_output=True,text=True,timeout=90)
            if proc.returncode: return {'status':'wsl_error','output':proc.stderr[-500:]}
            return json.loads(proc.stdout)
    rows=task_rows(args.n)
    corpus=json.dumps(rows,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode('utf8')
    local_files=('pal_campaign.py','pure_python.py','model_integrity.py','sandbox.py','sandbox_cli.py','sandbox_boot.sh','worker.py')
    protocol_hashes={name:hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() for name in local_files}
    meta={'gsm8k_revision':REV,'n_per_family':args.n,'dataset_split':'test','sample_seed':1414,
          'large_variant':'original final numeric answer multiplied by '+str(LARGE_FACTOR),
          'model_sha256':hashes,'runtime':runtime,'temperature':0,'generation_seed':1414,'max_tokens':512,
          'protocol_version':'pure-python-fsync-prefix-v5',
          'request_concurrency':args.concurrency,'context_per_slot':args.context_per_slot,
          'corpus_sha256':hashlib.sha256(corpus).hexdigest(),'protocol_sha256':protocol_hashes,
          'pure_python_sha256':protocol_hashes['pure_python.py']}
    if args.concurrency==2:generate=paired_prefetch(generate,rows,args.output,args.max_new)
    run(generate,evaluate,rows,args.output,meta,max_new=args.max_new)


if __name__=='__main__': main()
