"""Construye habilidades desde planes del currículo verificados, sin usar test."""
import argparse,hashlib,json
from pathlib import Path
from skill_library_env import SKILLS,make_tasks,recipe,execute
from skill_library_eval import MODEL,REV,MODEL_SHA,ATTEMPTS,TOTAL_BUDGET,OUTPUT_BUDGET,PER_ATTEMPT,validate_history

def derive(path,tokenizer):
    path=Path(path);raw=path.read_bytes();lines=raw.decode('utf8').splitlines()
    meta=json.loads(lines[0])['metadata'];tasks=make_tasks()[0]
    source=Path(__file__)
    if (meta['protocol'],meta['split'],meta['model'],meta['revision'],meta['expected_model_sha256'],meta['backend'])!=(3,'development',MODEL,REV,MODEL_SHA,'cuda'):
        raise ValueError('unexpected development protocol')
    if (meta['code_sha256']!=hashlib.sha256(source.with_name('skill_library_eval.py').read_bytes()).hexdigest()
        or meta['environment_sha256']!=hashlib.sha256(source.with_name('skill_library_env.py').read_bytes()).hexdigest()
        or meta['learning_sha256']!=hashlib.sha256(source.read_bytes()).hexdigest()):raise ValueError('protocol code differs')
    task_hash=hashlib.sha256(json.dumps(tasks,sort_keys=True,ensure_ascii=False).encode()).hexdigest()
    if (meta['task_sha256']!=task_hash or meta['task_count']!=len(tasks) or meta['conditions']!=['retry']
        or (meta['attempts'],meta['total_token_cap'],meta['output_token_allocation'],meta['output_cap_per_attempt'])
           !=(ATTEMPTS,TOTAL_BUDGET,OUTPUT_BUDGET,PER_ATTEMPT)
        or meta['sampling']!={'temperature':.7,'top_p':1.,'top_k':0,'min_p':None,'repetition_penalty':1.}
        or meta['eos_rule']!='únicamente tokenizer.eos_token_id'
        or meta['library_sha256'] is not None or meta['development_source_sha256'] is not None):
        raise ValueError('development task or conditions differ')
    rows={}
    for line in lines[1:]:
        row=json.loads(line);key=(row['task_id'],row['condition'])
        if key in rows:raise ValueError('duplicate row')
        rows[key]=row
    journal=Path(str(path)+'.calls.jsonl');jraw=journal.read_bytes();jlines=jraw.decode('utf8').splitlines()
    if json.loads(jlines[0])!={'metadata':meta}:raise ValueError('journal metadata differs')
    calls={}
    for line in jlines[1:]:
        event=json.loads(line);key=(event['task_id'],event['condition'],event['attempt'])
        if key in calls:raise ValueError('duplicate call')
        calls[key]=event
    validate_history(tasks,rows,calls,tokenizer,'development',('retry',),None)
    if len(rows)!=len(tasks) or len(calls)!=len(tasks)*ATTEMPTS:raise ValueError('development curriculum incomplete')
    skills=[];missing=[]
    for specification in SKILLS:
        family=[task for task in tasks if task['skill']==specification['id']]
        selected=None
        for task in family:
            row=rows[(task['id'],'retry')]
            for i,attempt in enumerate(row['attempts']):
                if attempt['verdict']['success']:
                    plan=json.loads(attempt['event']['text'])
                    selected={'id':specification['id'],'description':specification['description'],
                              'ops':[plan['steps'][0]['op'],plan['steps'][1]['op']],
                              'source_task_id':task['id'],'source_attempt':i}
                    break
            if selected:break
        if selected is None:missing.append(specification['id']);continue
        if not all(execute(recipe(selected,t['a'],t['b'],t['c']),t)['success'] for t in family):
            raise ValueError('candidate does not generalize within development family')
        skills.append(selected)
    return {'protocol':3,'model':MODEL,'revision':REV,'source_sha256':hashlib.sha256(raw).hexdigest(),
            'journal_sha256':hashlib.sha256(jraw).hexdigest(),'development_task_sha256':task_hash,
            'construction_tasks':len(tasks),'construction_calls':len(calls),
            'construction_input_tokens':sum(e['prompt_tokens'] for e in calls.values()),
            'construction_output_tokens':sum(e['output_tokens'] for e in calls.values()),
            'skills':skills,'missing_families':missing,
            'rule':'primer plan exitoso por familia en el currículo; operandos generalizados y '
                   'verificación en tareas de desarrollo; sin sustituir familias ausentes'}

if __name__=='__main__':
    from transformers import AutoTokenizer
    p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--output',required=True);args=p.parse_args()
    tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    result=derive(args.input,tok);out=Path(args.output)
    if out.exists():raise ValueError('refusing to overwrite')
    out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf8')
    print(json.dumps(result,ensure_ascii=False,indent=2))
