"""Control de sintaxis restringida en desarrollo; nunca consulta test."""
import argparse,hashlib,json,time
from pathlib import Path
import torch
from skill_library_env import make_tasks,messages
from skill_library_constraints import SyntaxConstraint,GRAMMAR,PATTERN
from skill_library_eval import (MODEL,REV,MODEL_SHA,ATTEMPTS,TOTAL_BUDGET,OUTPUT_BUDGET,
                                PER_ATTEMPT,unpack,digest,append,output_limit,seed_for,row_from_events)

def validate_history(tasks,rows,cached,tokenizer,constraint):
    indexed={task['id']:(i,task) for i,task in enumerate(tasks)}
    for (task_id,attempt),event in cached.items():
        if task_id not in indexed 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,'retry'),tokenize=True,add_generation_prompt=True)))
        sha=digest(json.dumps(prompt,separators=(',',':')).encode())
        previous=[cached.get((task_id,i)) for i in range(attempt)]
        if any(e is None for e 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('development',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')
        prefix=[]
        for i,token in enumerate(ids):
            if token not in constraint.allowed(prefix):raise ValueError('output violates grammar')
            if token==tokenizer.eos_token_id:
                if i!=len(ids)-1:raise ValueError('internal EOS')
            else:prefix.append(token)
        ended=bool(ids and ids[-1]==tokenizer.eos_token_id)
        text=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']!=text:
            raise ValueError('saved output and IDs differ')
        if ended and GRAMMAR.fullmatch(text) is None:raise ValueError('EOS before complete JSON')
    for task_id,row in rows.items():
        if task_id not in indexed:raise ValueError('unknown completed task')
        events=[cached.get((task_id,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],'retry',events)
        if expected['total_tokens']>TOTAL_BUDGET or expected['output_tokens']>OUTPUT_BUDGET or row!=expected:
            raise ValueError('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];tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    constraint=SyntaxConstraint(tokenizer,0);source=Path(__file__)
    task_sha=digest(json.dumps(tasks,sort_keys=True,ensure_ascii=False).encode())
    meta={'protocol':'4-syntax-control','model':MODEL,'revision':REV,'expected_model_sha256':MODEL_SHA,
          'backend':'cuda','split':'development','task_seed':3034,'task_sha256':task_sha,'task_count':len(tasks),
          'conditions':['retry'],'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 al completar gramática',
          'seed_rule':'4200 + índice * 3 + intento, igual que desarrollo v3',
          'v4_code_sha256':digest(source.read_bytes()),'constraint_sha256':digest(source.with_name('skill_library_constraints.py').read_bytes()),
          'v3_core_sha256':digest(source.with_name('skill_library_eval.py').read_bytes()),
          'environment_sha256':digest(source.with_name('skill_library_env.py').read_bytes()),
          'grammar':PATTERN,'grammar_scope':'JSON canónico, claves en orden fijo, sin espacios; no consulta tarea ni respuesta'}
    out=Path(args.output);journal=Path(str(out)+'.calls.jsonl');out.parent.mkdir(parents=True,exist_ok=True)
    rows={};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:]:
                item=json.loads(line);key=item['task_id'] if target=='rows' else (item['task_id'],item['attempt'])
                if key in (rows if target=='rows' else cached):raise ValueError('duplicate saved item')
                (rows if target=='rows' else cached)[key]=item
    validate_history(tasks,rows,cached,tokenizer,constraint)
    if len(rows)==len(tasks):print('desarrollo ya completo',flush=True);return
    weights=hf_hub_download(MODEL,filename='model.safetensors',revision=REV,local_files_only=True)
    with open(weights,'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 output,journal.open('a',encoding='utf8') as calls:
        if output.tell()==0:append(output,{'metadata':meta})
        if calls.tell()==0:append(calls,{'metadata':meta})
        added=0
        for index,task in enumerate(tasks):
            if task['id'] in rows:continue
            prompt=list(unpack(tokenizer.apply_chat_template(messages(task,'retry'),tokenize=True,add_generation_prompt=True)))
            prompt_sha=digest(json.dumps(prompt,separators=(',',':')).encode());constraint.prompt_length=len(prompt)
            events=[];spent=output_spent=0
            for attempt in range(ATTEMPTS):
                seed=seed_for('development',index,attempt);key=(task['id'],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()
                    prev_count=constraint.callback_count;prev_seconds=constraint.callback_seconds
                    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.,
                            max_new_tokens=available,eos_token_id=tokenizer.eos_token_id,pad_token_id=tokenizer.eos_token_id,
                            prefix_allowed_tokens_fn=constraint)
                    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()
                    if ended and GRAMMAR.fullmatch(text) is None:raise ValueError('completed output violates grammar')
                    free,total=torch.cuda.mem_get_info()
                    event={'task_id':task['id'],'condition':'retry','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,
                           'constraint_callbacks':constraint.callback_count-prev_count,
                           'constraint_seconds':constraint.callback_seconds-prev_seconds,
                           '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,'retry',events)
            if spent>TOTAL_BUDGET or output_spent>OUTPUT_BUDGET:raise ValueError('budget exceeded')
            append(output,row);print('development',index,'retry',row['success_at_3'],spent,flush=True)
            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('--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)
