"""Currículo y comparación de habilidades con presupuesto contabilizado en CUDA."""
import argparse,hashlib,json,os,time
from pathlib import Path
import torch
from skill_library_env import make_tasks,messages,parse_response

MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
MODEL_SHA='fdf756fa7fcbe7404d5c60e26bff1a0c8b8aa1f72ced49e7dd0210fe288fb7fe'
ATTEMPTS=3
TOTAL_BUDGET=900
OUTPUT_BUDGET=384
PER_ATTEMPT=192

def unpack(value):return value['input_ids'] if hasattr(value,'keys') else value
def digest(value):return hashlib.sha256(value).hexdigest()
def append(stream,value):
    stream.write(json.dumps(value,ensure_ascii=False)+'\n');stream.flush();os.fsync(stream.fileno())

def output_limit(prompt_tokens,spent,output_spent,attempt):
    if any(type(v) is not int or v<0 for v in (prompt_tokens,spent,output_spent,attempt)) or attempt>=ATTEMPTS:
        raise ValueError('invalid budget state')
    future=ATTEMPTS-attempt-1
    # Reserva prompt y al menos un token de salida para cada intento restante.
    limit=min(PER_ATTEMPT,TOTAL_BUDGET-spent-(future+1)*prompt_tokens-future,
              OUTPUT_BUDGET-output_spent-future)
    if limit<1:raise ValueError('budget cannot fund remaining attempts')
    return limit

def seed_for(split,index,attempt):return (4200 if split=='development' else 5200)+index*ATTEMPTS+attempt

def row_from_events(task,condition,events):
    attempts=[]
    for event in events:
        verdict=parse_response(event['text'],task) if event['end_reason']=='eos' else {'success':False,'error':'truncated'}
        attempts.append({'event':event,'verdict':verdict})
    return {'task_id':task['id'],'condition':condition,'attempts':attempts,
            **{f'success_at_{k}':any(a['verdict']['success'] for a in attempts[:k]) for k in range(1,ATTEMPTS+1)},
            'input_tokens':sum(e['prompt_tokens'] for e in events),
            'output_tokens':sum(e['output_tokens'] for e in events),
            'total_tokens':sum(e['prompt_tokens']+e['output_tokens'] for e in events)}

def validate_history(tasks,rows,cached,tokenizer,split,conditions,library):
    indexed={task['id']:(i,task) for i,task in enumerate(tasks)}
    if len(indexed)!=len(tasks):raise ValueError('duplicate task IDs')
    for (task_id,condition,attempt),event in cached.items():
        if task_id not in indexed or condition not in conditions or attempt not in range(ATTEMPTS):raise ValueError('unknown saved call')
        index,task=indexed[task_id]
        prompt=list(unpack(tokenizer.apply_chat_template(messages(task,condition,library),tokenize=True,add_generation_prompt=True)))
        sha=digest(json.dumps(prompt,separators=(',',':')).encode())
        previous=[cached.get((task_id,condition,i)) for i in range(attempt)]
        if any(item is None for item in previous):raise ValueError('attempt without previous calls')
        spent=sum(e['prompt_tokens']+e['output_tokens'] for e in previous)
        output_spent=sum(e['output_tokens'] for e in previous)
        limit=output_limit(len(prompt),spent,output_spent,attempt)
        if (event['seed'],event['prompt_sha256'],event['prompt_tokens'],event['output_limit'])!=(seed_for(split,index,attempt),sha,len(prompt),limit):
            raise ValueError('saved call differs from planned input')
        ids=event['output_ids']
        if not isinstance(ids,list) or any(type(x) is not int for x in ids) or event['output_tokens']!=len(ids) or len(ids)>limit:
            raise ValueError('invalid saved output IDs')
        ended=bool(ids and ids[-1]==tokenizer.eos_token_id)
        decoded=tokenizer.decode(ids,skip_special_tokens=True,clean_up_tokenization_spaces=False).strip()
        if event['end_reason']!=('eos' if ended else 'length') or event['text']!=decoded:
            raise ValueError('saved output and IDs differ')
    for (task_id,condition),row in rows.items():
        if task_id not in indexed or condition not in conditions:raise ValueError('unknown completed row')
        events=[cached.get((task_id,condition,i)) for i in range(ATTEMPTS)]
        if any(event is None for event in events):raise ValueError('completed row lacks journal entries')
        expected=row_from_events(indexed[task_id][1],condition,events)
        if expected['total_tokens']>TOTAL_BUDGET or expected['output_tokens']>OUTPUT_BUDGET or row!=expected:
            raise ValueError('completed row disagrees with journal')

def run(args):
    if not torch.cuda.is_available():raise RuntimeError('CUDA requerida')
    from transformers import AutoModelForCausalLM,AutoTokenizer
    from huggingface_hub import hf_hub_download
    tasks=make_tasks()[0 if args.split=='development' else 1]
    conditions=('retry',) if args.split=='development' else ('retry','library')
    tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    library=None;library_sha=None;dev_sha=None
    if args.split=='test':
        if not args.library or not args.development_input:raise ValueError('test requires frozen library and development journal')
        from skill_library_learn import derive
        path=Path(args.library);library_raw=path.read_bytes();learned=json.loads(library_raw)
        recomputed=derive(args.development_input,tokenizer)
        if learned!=recomputed:raise ValueError('library differs from verified development data')
        library=learned['skills'];library_sha=digest(library_raw);dev_sha=learned['source_sha256']
    elif args.library or args.development_input:raise ValueError('development does not consume a library')
    task_hash=digest(json.dumps(tasks,sort_keys=True,ensure_ascii=False).encode())
    source=Path(__file__)
    meta={'protocol':3,'model':MODEL,'revision':REV,'expected_model_sha256':MODEL_SHA,'backend':'cuda',
          'code_sha256':digest(source.read_bytes()),
          'environment_sha256':digest(source.with_name('skill_library_env.py').read_bytes()),
          'learning_sha256':digest(source.with_name('skill_library_learn.py').read_bytes()),
          'task_seed':3034,'split':args.split,'task_sha256':task_hash,'task_count':len(tasks),
          'library_sha256':library_sha,'development_source_sha256':dev_sha,
          'conditions':list(conditions),'attempts':ATTEMPTS,'total_token_cap':TOTAL_BUDGET,
          'output_token_allocation':OUTPUT_BUDGET,'output_cap_per_attempt':PER_ATTEMPT,
          'sampling':{'temperature':.7,'top_p':1.,'top_k':0,'min_p':None,'repetition_penalty':1.},
          'eos_rule':'únicamente tokenizer.eos_token_id',
          'seed_rule':'base 4200 desarrollo o 5200 test + índice * 3 + intento; compartida por condición'}
    out=Path(args.output);journal=Path(str(out)+'.calls.jsonl');out.parent.mkdir(parents=True,exist_ok=True)
    completed={};cached={}
    for path,target in ((out,'rows'),(journal,'calls')):
        if path.exists() and path.stat().st_size:
            lines=path.read_text(encoding='utf8').splitlines()
            if json.loads(lines[0])!={'metadata':meta}:raise ValueError('configuration mismatch')
            for line in lines[1:]:
                row=json.loads(line);key=(row['task_id'],row['condition'])
                if target=='rows':
                    if key in completed:raise ValueError('duplicate task condition')
                    completed[key]=row
                else:
                    key=(*key,row['attempt'])
                    if key in cached:raise ValueError('duplicate call')
                    cached[key]=row
    validate_history(tasks,completed,cached,tokenizer,args.split,conditions,library)
    if len(completed)==len(tasks)*len(conditions):print('evaluación ya completa',flush=True);return
    weight_path=hf_hub_download(MODEL,filename='model.safetensors',revision=REV,local_files_only=True)
    with open(weight_path,'rb') as stream:
        if hashlib.file_digest(stream,'sha256').hexdigest()!=MODEL_SHA:raise ValueError('model hash mismatch')
    torch.cuda.reset_peak_memory_stats()
    model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=True,
                                               dtype=torch.bfloat16).to('cuda').eval()
    with out.open('a',encoding='utf8') as rows,journal.open('a',encoding='utf8') as calls:
        if rows.tell()==0:append(rows,{'metadata':meta})
        if calls.tell()==0:append(calls,{'metadata':meta})
        added=0
        for index,task in enumerate(tasks):
            new_task=False
            for condition in conditions:
                if (task['id'],condition) in completed:continue
                new_task=True
                prompt=list(unpack(tokenizer.apply_chat_template(messages(task,condition,library),tokenize=True,add_generation_prompt=True)))
                prompt_sha=digest(json.dumps(prompt,separators=(',',':')).encode())
                events=[];spent=output_spent=0
                for attempt in range(ATTEMPTS):
                    seed=seed_for(args.split,index,attempt);key=(task['id'],condition,attempt)
                    available=output_limit(len(prompt),spent,output_spent,attempt)
                    if key in cached:event=cached[key]
                    else:
                        torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
                        x=torch.tensor([prompt],device='cuda');start=time.perf_counter()
                        with torch.inference_mode():
                            result=model.generate(input_ids=x,attention_mask=torch.ones_like(x),do_sample=True,
                                temperature=.7,top_p=1.,top_k=0,min_p=None,repetition_penalty=1.0,
                                max_new_tokens=available,eos_token_id=tokenizer.eos_token_id,
                                pad_token_id=tokenizer.eos_token_id)
                        generated=result[0,len(prompt):].tolist();torch.cuda.synchronize()
                        ended=bool(generated and generated[-1]==tokenizer.eos_token_id)
                        text=tokenizer.decode(generated,skip_special_tokens=True,clean_up_tokenization_spaces=False).strip()
                        free,total=torch.cuda.mem_get_info()
                        event={'task_id':task['id'],'condition':condition,'attempt':attempt,'seed':seed,
                               'prompt_sha256':prompt_sha,'prompt_tokens':len(prompt),'output_limit':available,
                               'output_ids':generated,'output_tokens':len(generated),'text':text,
                               'end_reason':'eos' if ended else 'length','seconds':time.perf_counter()-start,
                               'peak_allocated_bytes':torch.cuda.max_memory_allocated(),
                               'peak_reserved_bytes':torch.cuda.max_memory_reserved(),
                               'cuda_free_bytes':free,'cuda_total_bytes':total}
                        append(calls,event)
                    spent+=event['prompt_tokens']+event['output_tokens'];output_spent+=event['output_tokens'];events.append(event)
                row=row_from_events(task,condition,events)
                if spent>TOTAL_BUDGET or output_spent>OUTPUT_BUDGET:raise ValueError('budget exceeded')
                append(rows,row);print(args.split,index,condition,row['success_at_3'],spent,flush=True)
            if new_task:
                added+=1
                if args.max_tasks is not None and added>=args.max_tasks:return

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--output',required=True)
    p.add_argument('--split',required=True,choices=('development','test'))
    p.add_argument('--library');p.add_argument('--development-input')
    p.add_argument('--max-tasks',type=int,help='completar este número de tareas nuevas y detenerse')
    args=p.parse_args()
    if args.max_tasks is not None and args.max_tasks<1:raise ValueError('invalid block size')
    run(args)
