"""Recoge episodios con profesor 7B en localhost; no ajusta ningún modelo."""
import argparse
import json
import os
from pathlib import Path
import time
from urllib.request import Request,ProxyHandler,HTTPRedirectHandler,build_opener
from environment import episode,split_tasks

MODEL='qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf'
REV='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
WEIGHTS_SHA256=['dfce12e3862a5283ccfb88221b48480e58745165de856439950d0f22590580db',
                '539cf93f78e887edea1c04e2d7d8cdaca9d01dae9c9025bcb8accbe29df3d72a']

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self,*a,**k):raise RuntimeError('redirect prohibited')

def generate(messages,seed,port):
    # Tool observations are user messages in this simple text protocol; they remain
    # environment tokens when a later chat template constructs the loss mask.
    messages=[{'role':'user' if m['role']=='tool' else m['role'],'content':m['content']} for m in messages]
    payload={'model':MODEL,'messages':messages,'temperature':.7,'top_p':1.,'top_k':0,'min_p':.05,
             'repeat_penalty':1.,'seed':seed,'max_tokens':96}
    req=Request(f'http://127.0.0.1:{port}/v1/chat/completions',data=json.dumps(payload).encode(),
                headers={'Content-Type':'application/json'})
    start=time.perf_counter()
    with build_opener(ProxyHandler({}),NoRedirect()).open(req,timeout=900) as response:data=json.load(response)
    if data.get('model')!=MODEL:raise ValueError('unexpected model')
    choice=data['choices'][0]
    usage=dict(data.get('usage',{}))
    usage['finish_reason']=choice.get('finish_reason')
    usage['wall_seconds']=time.perf_counter()-start
    usage['system_fingerprint']=data.get('system_fingerprint')
    usage['generation_settings']=data.get('__verbose',{}).get('generation_settings')
    return choice['message'].get('content') or '',usage

def validate_rows(rows,splits):
    expected={(partition,task['id']):task
              for partition,group in zip(('train','validation','test'),splits) for task in group}
    done=set()
    for row in rows:
        key=(row.get('split'),row.get('task',{}).get('id'))
        if key not in expected or key in done or row['task']!=expected[key]:
            raise ValueError('unknown, duplicate or altered task')
        trace=row.get('trace',{});messages=trace.get('messages',[])
        if (not isinstance(messages,list) or len(messages)!=5 or
            not all(isinstance(m,dict) for m in messages) or
            messages[1].get('role')!='assistant' or messages[4].get('role')!='assistant'):
            raise ValueError('invalid trajectory structure')
        outputs=iter((messages[1]['content'],messages[4]['content']))
        if episode(row['task'],lambda _:next(outputs))!=trace:
            raise ValueError('trajectory or reward disagrees with environment')
        usage=row.get('usage')
        if not isinstance(usage,list) or len(usage)!=2 or any(
            not isinstance(item,dict) or type(item.get('total_tokens')) is not int or item['total_tokens']<0 for item in usage):
            raise ValueError('invalid trajectory usage')
        done.add(key)
    return done

def collect(output,generate_fn,train=512,validation=64,test=64,seed=3030,max_new=None,backend='unverified'):
    if backend not in ('cpu','cuda','unverified'):raise ValueError('invalid backend')
    splits=split_tasks(train,validation,test,seed)
    metadata={'model':MODEL,'revision':REV,'seed':seed,'split_sizes':[train,validation,test],
              'temperature':.7,'top_p':1.,'top_k':0,'min_p':.05,'repeat_penalty':1.,'max_tokens':96,
              'backend':backend,
              'protocol':4,'expected_model_sha256':WEIGHTS_SHA256,
              'seed_rule':'seed + 2 * global task index + turn index'}
    path=Path(output);done=set()
    if path.exists() and path.stat().st_size:
        lines=path.read_text(encoding='utf8').splitlines()
        if json.loads(lines[0])!={'metadata':metadata}:raise ValueError('configuration mismatch')
        done=validate_rows([json.loads(line) for line in lines[1:]],splits)
    journal=Path(str(path)+'.calls.jsonl')
    events=[]
    if journal.exists() and journal.stat().st_size:
        lines=journal.read_text(encoding='utf8').splitlines()
        if json.loads(lines[0])!={'metadata':metadata}:raise ValueError('call journal configuration mismatch')
        events=[json.loads(line) for line in lines[1:]]
    elif done:
        raise ValueError('call journal missing for an existing collection')
    with path.open('a',encoding='utf8') as out, journal.open('a',encoding='utf8') as calls:
        if out.tell()==0:
            out.write(json.dumps({'metadata':metadata})+'\n');out.flush();os.fsync(out.fileno())
        if calls.tell()==0:
            calls.write(json.dumps({'metadata':metadata})+'\n');calls.flush();os.fsync(calls.fileno())
        written=0
        offset=0
        for partition,group in zip(('train','validation','test'),splits):
            for index,task in enumerate(group):
                if (partition,task['id']) in done:continue
                costs=[]
                # If the last durable response is the first turn of this
                # unfinished episode, reuse exactly that response and usage.
                # Other journal shapes are not inferred or reconstructed.
                reusable=[events[-1]] if events else []
                def agent(messages):
                    turn=len(costs)
                    call_seed=seed+(offset+index)*2+turn
                    event=reusable[0] if turn==0 and reusable else None
                    if (event and (event.get('split'),event.get('task_id'),event.get('turn'),event.get('seed'))
                        ==(partition,task['id'],0,call_seed) and isinstance(event.get('content'),str)
                        and isinstance(event.get('usage'),dict)
                        and type(event['usage'].get('total_tokens')) is int and event['usage']['total_tokens']>=0):
                        text,usage=event['content'],event['usage']
                        reusable.clear()
                    else:
                        text,usage=generate_fn(messages,call_seed)
                        # Persist each completed call before starting the next turn.
                        calls.write(json.dumps({'split':partition,'task_id':task['id'],
                                                'turn':turn,'seed':call_seed,'content':text,
                                                'usage':usage},ensure_ascii=False)+'\n')
                        calls.flush();os.fsync(calls.fileno())
                    if type(usage.get('total_tokens')) is not int or usage['total_tokens']<0:
                        raise RuntimeError('model token usage missing or invalid')
                    costs.append(usage);return text
                trace=episode(task,agent)
                row={'split':partition,'task':task,'trace':trace,'usage':costs}
                out.write(json.dumps(row,ensure_ascii=False)+'\n');out.flush();os.fsync(out.fileno())
                written+=1
                print(partition,index,trace['reward'],flush=True)
                if max_new is not None and written>=max_new:return
            offset+=len(group)

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--output',required=True)
    parser.add_argument('--port',type=int,default=11441)
    parser.add_argument('--backend',required=True,choices=('cpu','cuda'),help='backend verificado del servidor')
    parser.add_argument('--max-new',type=int,help='guardar este bloque y detenerse; omitir para la colección completa')
    args=parser.parse_args()
    if args.max_new is not None and args.max_new<1:raise ValueError('max-new must be positive')
    collect(args.output,lambda messages,seed:generate(messages,seed,args.port),max_new=args.max_new,backend=args.backend)
