"""LLM local -> política por instrucción -> verificador VLM; ejecutar solo con checkpoint final."""
import argparse,gc,hashlib,json,os,re,sys,time
from pathlib import Path
import numpy as np
import torch
import mujoco
from PIL import Image
from verifier_prompt import verifier_question
from render_reference import paired_view
from transformers import AutoTokenizer,AutoModelForCausalLM,AutoProcessor,AutoModelForImageTextToText

for path in ('public/data/p13/l02','public/data/p13/l06','public/data/p13/l07','public/data/p13/l08','public/data/p13/l09'):
    sys.path.insert(0,str(Path(path).resolve()))
from language_tasks import LanguageTask,INSTRUCTIONS
import p13_pusht as base
assert 'offwidth="256" offheight="256"' in base.PUSHT_XML
base.PUSHT_XML=base.PUSHT_XML.replace('offwidth="256" offheight="256"','offwidth="384" offheight="384"')
from text_diffusion_model import TextDiffusionPolicy,text_embeddings
from diffusion_model import cosine_alphas,ddim

parser=argparse.ArgumentParser()
parser.add_argument('--policy',required=True);parser.add_argument('--policy-type',choices=['diffusion','smolvla','lora'],default='diffusion')
parser.add_argument('--text-model');parser.add_argument('--text-revision');parser.add_argument('--llm',required=True)
parser.add_argument('--smolvla-base');parser.add_argument('--smolvla-backbone');parser.add_argument('--blue');parser.add_argument('--orange')
parser.add_argument('--vlm',required=True)
parser.add_argument('--verifier-calibration',required=True,help='umbral ajustado únicamente con imágenes de calibración')
parser.add_argument('--output',required=True);parser.add_argument('--episodes',type=int,default=50)
parser.add_argument('--device',choices=['cpu','cuda'],default='cpu');parser.add_argument('--paired-reference',action='store_true');parser.add_argument('--profile-seed',type=int);parser.add_argument('--resume',action='store_true')
args=parser.parse_args();torch.set_num_threads(1);device=torch.device(args.device)
if device.type=='cuda' and not torch.cuda.is_available():raise RuntimeError('CUDA no disponible')
if args.profile_seed is not None and (args.profile_seed<0 or 72000<=args.profile_seed<72000+args.episodes):parser.error('Perfil debe quedar fuera de la reserva')
def log_memory(stage):
    if device.type=='cuda':
        torch.cuda.synchronize(device);free,total=torch.cuda.mem_get_info(device)
        print('MEMORIA',stage,'asignado',torch.cuda.memory_allocated(device),'reservado',torch.cuda.memory_reserved(device),'libre_global_cuda',free,'total',total,flush=True)
    else:print('MEMORIA',stage,'cpu',flush=True)

tokenizer=AutoTokenizer.from_pretrained(args.llm,local_files_only=True)
llm=AutoModelForCausalLM.from_pretrained(args.llm,local_files_only=True,torch_dtype=torch.float32).to(device).eval();log_memory('qwen cargado')
names=['azul','naranja'];instructions=['Primero empuja la T a la meta azul y después a la naranja.',
                                        'Primero empuja la T a la meta naranja y después a la azul.']
def decompose(instruction):
    prompt=('Return only a JSON list with two strings chosen from "azul" and "naranja", in the order requested. '
            'Do not add text. Instruction: '+instruction)
    text=tokenizer.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
    inputs=tokenizer(text,return_tensors='pt').to(device)
    with torch.no_grad():generated=llm.generate(**inputs,max_new_tokens=40,do_sample=False)
    answer=tokenizer.decode(generated[0,inputs['input_ids'].shape[1]:],skip_special_tokens=True).strip()
    # Aceptar un único bloque JSON cercado sin alterar el contenido ni el orden.
    fenced=re.fullmatch(r'```(?:json)?\s*(.*?)\s*```',answer,flags=re.IGNORECASE|re.DOTALL)
    payload=fenced.group(1) if fenced else answer
    try:plan=json.loads(payload)
    except json.JSONDecodeError:return answer,None
    if not isinstance(plan,list) or len(plan)!=2 or any(x not in names for x in plan) or plan[0]==plan[1]:return answer,None
    return answer,plan
plans={instruction:decompose(instruction) for instruction in instructions}
del llm,tokenizer;gc.collect()
if device.type=='cuda':torch.cuda.empty_cache()
log_memory('qwen liberado')
ck=torch.load(args.policy,map_location='cpu',weights_only=False)
if args.policy_type=='diffusion':
    if not args.text_model or not args.text_revision:parser.error('difusión necesita --text-model y --text-revision')
    texts=text_embeddings([INSTRUCTIONS['azul'],INSTRUCTIONS['naranja']],args.text_model,args.text_revision)
    if not torch.allclose(texts,ck['reference_embeddings'],atol=1e-5,rtol=1e-5):raise ValueError('codificador de texto incompatible con checkpoint')
    actor=TextDiffusionPolicy().to(device);actor.load_state_dict(ck['weights']);actor.eval();alphas=cosine_alphas(100).to(device)
else:
    if not args.smolvla_base or not args.smolvla_backbone:parser.error('SmolVLA necesita --smolvla-base y --smolvla-backbone')
    sys.path.insert(0,str(Path(os.environ.get('ORYON_L32_CODE_DIR','public/data/m24/l32')).resolve()))
    from draccus.parsers.decoding import decode
    from lerobot.policies.smolvla.configuration_smolvla import SmolVLAConfig
    from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy
    from smolvla_adapter import IMAGE_KEY,configure_2d
    if args.policy_type=='lora':
        if not args.blue or not args.orange:parser.error('LoRA necesita --blue y --orange')
        from load_shared_lora import load_shared_lora
        actor,_=load_shared_lora(args.smolvla_base,args.smolvla_backbone,args.policy,args.blue,args.orange,device)
    else:
        raw=json.loads((Path(args.smolvla_base)/'config.json').read_text(encoding='utf8'))
        if raw.pop('type')!='smolvla':raise ValueError('Tipo de modelo incompatible')
        cfg=decode(SmolVLAConfig,raw);cfg.load_vlm_weights=False;cfg.vlm_model_name=str(Path(args.smolvla_backbone).resolve());cfg.device='cpu'
        actor=SmolVLAPolicy(cfg);configure_2d(actor,ck['stats']);actor.load_state_dict(ck['weights'],strict=True);actor=actor.to(device).eval()
ck.pop('weights',None);ck.pop('trainable',None);gc.collect();log_memory('actor cargado')
processor=AutoProcessor.from_pretrained(args.vlm,local_files_only=True)
processor.image_processor.do_image_splitting=False
processor.image_processor.size={'longest_edge':512}
vlm=AutoModelForImageTextToText.from_pretrained(args.vlm,local_files_only=True,torch_dtype=torch.float32).to(device).eval();log_memory('actor y VLM cargados')
assert all(next(model.parameters()).device.type==device.type for model in (actor,vlm))
calibration=json.loads(Path(args.verifier_calibration).read_text(encoding='utf8'));threshold=float(calibration['threshold'])
expected_size=[768,768] if args.paired_reference else [384,384]
expected_questions=sorted(verifier_question(goal,args.paired_reference) for goal in ('azul','naranja'))
if calibration.get('image_size')!=expected_size or calibration.get('questions')!=expected_questions:raise ValueError('Calibración incompatible con imagen o prompt actual')
def first_token_ids(words):
    ids=set()
    for word in words:
        tokens=processor.tokenizer(word,add_special_tokens=False).input_ids
        if len(tokens)==1:ids.add(tokens[0])
    if not ids:raise ValueError('no hay token único para respuesta')
    return sorted(ids)
yes_ids=first_token_ids(('Yes','yes',' Yes',' yes'));no_ids=first_token_ids(('No','no',' No',' no'))
if set(yes_ids)&set(no_ids):raise ValueError('conjuntos de tokens solapados')
def verify(image,goal):
    question=verifier_question(goal,args.paired_reference)
    pil_image=image if isinstance(image,Image.Image) else Image.fromarray(image)
    messages=[{'role':'user','content':[{'type':'image','image':pil_image},{'type':'text','text':question}]}]
    inputs=processor.apply_chat_template(messages,add_generation_prompt=True,tokenize=True,return_dict=True,return_tensors='pt').to(device)
    start=time.perf_counter()
    with torch.no_grad():output=vlm.generate(**inputs,max_new_tokens=1,do_sample=False,return_dict_in_generate=True,output_scores=True)
    seconds=time.perf_counter()-start
    answer=processor.decode(output.sequences[0,inputs['input_ids'].shape[1]:],skip_special_tokens=True).strip()
    logits=output.scores[0][0].float();log_yes=torch.logsumexp(logits[yes_ids],0);log_no=torch.logsumexp(logits[no_ids],0)
    score=float(torch.sigmoid(log_yes-log_no))
    if not np.isfinite(score):return None,answer,seconds,None
    return score>=threshold,answer,seconds,score
@torch.no_grad()
def chunk(obs,goal,seed):
    im=torch.as_tensor(obs['observation.image'].transpose(2,0,1).copy(),dtype=torch.float32,device=device)[None]/255
    if args.policy_type in ('smolvla','lora'):
        torch.manual_seed(seed)
        if device.type=='cuda':torch.cuda.manual_seed(seed)
        batch={IMAGE_KEY:im,'observation.state':torch.as_tensor(obs['observation.state'],dtype=torch.float32,device=device)[None],
               'task':[INSTRUCTIONS[goal]]}
        actions=actor.predict_action_chunk(batch)[0].float().cpu().numpy()
        if actions.shape!=(16,2) or not np.isfinite(actions).all():raise ValueError('Chunk SmolVLA incompatible')
        return actions[:8]
    st=torch.as_tensor((obs['observation.state']-ck['mean'])/ck['std'],dtype=torch.float32,device=device)[None]
    embedding=texts[names.index(goal):names.index(goal)+1].to(device)
    generator=torch.Generator(device=device).manual_seed(seed)
    sample=ddim(lambda x,k,i,s:actor(x,k,i,s,embedding),im,st,alphas,16,2,10,generator)[0].cpu().numpy()
    return (np.clip(sample[:8],-1,1)+1)*ck['span']/2+ck['low']

def file_sha(path):
    with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
contract={'agent_source_sha256':file_sha(__file__),'prompt_source_sha256':file_sha(Path(__file__).with_name('verifier_prompt.py')),
          'render_source_sha256':file_sha(Path(__file__).with_name('render_reference.py')),
          'policy_type':args.policy_type,'policy_sha256':file_sha(args.policy),'llm_sha256':file_sha(Path(args.llm)/'model.safetensors'),
          'vlm_sha256':file_sha(Path(args.vlm)/'model.safetensors'),'calibration_sha256':file_sha(args.verifier_calibration),
          'llm_tokenizer_sha256':file_sha(Path(args.llm)/'tokenizer.json'),
          'vlm_tokenizer_sha256':file_sha(Path(args.vlm)/'tokenizer.json'),
          'vlm_preprocessor_sha256':file_sha(Path(args.vlm)/'preprocessor_config.json'),
          'vlm_processor_sha256':file_sha(Path(args.vlm)/'processor_config.json'),
          'text_model':args.text_model,'text_revision':args.text_revision,'episodes':args.episodes,'device':str(device),
          'paired_reference':args.paired_reference,'torch':torch.__version__,'seed_start':72000,'profile_seed':args.profile_seed,
          'max_steps_per_goal':120,'verifier_period':10,'first_verifier_step':10,'physical_success_coverage':float(base.EmpujeT.umbral),
          'smolvla_config_sha256':file_sha(Path(args.smolvla_base)/'config.json') if args.policy_type in ('smolvla','lora') else None,
          'smolvla_backbone_config_sha256':file_sha(Path(args.smolvla_backbone)/'config.json') if args.policy_type in ('smolvla','lora') else None,
          'smolvla_backbone_tokenizer_sha256':file_sha(Path(args.smolvla_backbone)/'tokenizer.json') if args.policy_type in ('smolvla','lora') else None}
output=Path(args.output);profile_file=Path(args.output+'.profile.json');records=[]
if args.resume and output.exists():
    saved=json.loads(output.read_text(encoding='utf8'))
    if saved.get('contract')!=contract:raise ValueError('Contrato de agente incompatible con resultados previos')
    records=saved['records']
    expected_keys=[(instruction,72000+i) for instruction in instructions for i in range(args.episodes)]
    if len(records)>len(expected_keys) or [(r['instruction'],r['seed']) for r in records]!=expected_keys[:len(records)]:
        raise ValueError('Secuencia de episodios incompatible')
    print('Reanudando desde',len(records),'episodios',flush=True)
if args.profile_seed is not None and profile_file.exists():
    previous_profile=json.loads(profile_file.read_text(encoding='utf8'))
    if previous_profile['seed']!=args.profile_seed or previous_profile['policy_sha256']!=contract['policy_sha256'] or previous_profile['agent_source_sha256']!=contract['agent_source_sha256']:
        raise ValueError('Perfil previo incompatible')
if args.profile_seed is not None and records and not profile_file.exists():raise ValueError('Falta perfil previo a episodios reservados')
profile_pending=args.profile_seed is not None and not records and not profile_file.exists()
def save_profile(record,started):
    value={'seed':record['seed'],'instruction':record['instruction'],'steps':record.get('steps',0),'seconds':time.perf_counter()-started,
           'checks':len(record['checks']),'policy_sha256':contract['policy_sha256'],'agent_source_sha256':contract['agent_source_sha256'],
           'peak_cuda_allocated_bytes':torch.cuda.max_memory_allocated(device) if device.type=='cuda' else None,
           'peak_cuda_reserved_bytes':torch.cuda.max_memory_reserved(device) if device.type=='cuda' else None,
           'note':'episodio adicional fuera de reserva; no integra los resultados'}
    profile_file.parent.mkdir(parents=True,exist_ok=True);tmp=profile_file.with_suffix(profile_file.suffix+'.tmp')
    tmp.write_text(json.dumps(value,indent=2),encoding='utf8');tmp.replace(profile_file);print('Perfil fuera de reserva',json.dumps(value),flush=True)
def save_records():
    output.parent.mkdir(parents=True,exist_ok=True)
    temporary=output.with_suffix(output.suffix+'.tmp')
    temporary.write_text(json.dumps({'contract':contract,'records':records},ensure_ascii=False,indent=2),encoding='utf8');temporary.replace(output)
for instruction_index,instruction in enumerate(instructions):
    raw,plan=plans[instruction]
    print('plan',instruction,repr(raw),flush=True)
    prior=[r for r in records if r['instruction']==instruction]
    if prior and any(r['raw_plan']!=raw or r['plan']!=plan for r in prior):raise ValueError('El plan generado cambió al reanudar')
    expected=[['azul','naranja'],['naranja','azul']][instruction_index]
    sequence=([-1] if instruction_index==0 and profile_pending else [])+list(range(args.episodes))
    for episode in sequence:
        profiling=episode==-1;seed=args.profile_seed if profiling else 72000+episode
        if not profiling and episode<len(prior):continue
        started=time.perf_counter()
        record={'instruction':instruction,'expected':expected,'raw_plan':raw,'plan':plan,'seed':seed,'checks':[],'success':False}
        if plan is None:
            record['failure']='plan inválido'
            if profiling:save_profile(record,started);continue
            records.append(record);save_records();continue
        task=LanguageTask(plan[0]);task.reiniciar(seed);high_renderer=mujoco.Renderer(task.env.model,384,384);total_steps=0;clipped_steps=0;completed=True
        for stage,goal in enumerate(plan):
            if args.policy_type in ('smolvla','lora'):actor.reset()
            task.goal=goal;pending=[];verified=False
            for t in range(120):
                obs=task.observar(True)
                if t>0 and t%10==0:
                    if args.paired_reference:image_for_verifier=paired_view(task,high_renderer)
                    else:
                        high_renderer.update_scene(task.env.data,camera='arriba');image_for_verifier=np.flipud(high_renderer.render()).copy()
                    decision,answer,seconds,score=verify(image_for_verifier,goal);coverage=float(task.coverage());actual=coverage>=task.env.umbral
                    record['checks'].append({'stage':stage,'t':t,'vlm':decision,'answer':answer,'score':score,'seconds':seconds,'coverage_for_evaluation':coverage,'oracle_for_evaluation':bool(actual)})
                    if decision is True:verified=True;break
                    if decision is None:record['failure']='puntuación del verificador no finita';break
                if not pending:pending=list(chunk(obs,goal,seed+1000*stage+t))
                proposed=np.clip(pending.pop(0),0,512)
                previous=obs['observation.state'];delta=proposed-previous;norm=np.linalg.norm(delta)
                if norm>50:proposed=previous+delta*(50/norm);clipped_steps+=1
                task.actuar(proposed);total_steps+=1
            if not verified:completed=False;record.setdefault('failure','subtarea no verificada');break
            # No conservar un chunk de la meta anterior: la nueva instrucción cambia el control.
            pending=[]
        record['success']=bool(completed and plan==expected and all(check['oracle_for_evaluation'] for check in record['checks'] if check['vlm'] is True))
        record['steps']=total_steps;record['limited_steps']=clipped_steps
        high_renderer.close()
        if task.env.renderer is not None:task.env.renderer.close()
        if profiling:save_profile(record,started);continue
        records.append(record);print('episodio',seed,'éxito',record['success'],'pasos',total_steps,flush=True)
        save_records()
save_records()
print('totales',sum(r['success'] for r in records),'/',len(records))
