"""Referencia textual T/L, mismas semillas seleccionadas geométricamente para l32."""
import argparse,hashlib,json,os,subprocess,sys
from pathlib import Path

CASES=(('t','azul','Empuja la T hasta la meta azul'),('t','naranja','Empuja la T hasta la meta naranja'),
       ('l','azul','Empuja la pieza en forma de L hasta la meta azul'),
       ('l','naranja','Empuja la pieza en forma de L hasta la meta naranja'))
p=argparse.ArgumentParser();p.add_argument('--script',required=True);p.add_argument('--checkpoint',required=True)
p.add_argument('--seeds-json',required=True);p.add_argument('--out',required=True);p.add_argument('--device',choices=['cpu','cuda'],default='cpu')
p.add_argument('--wrapper',help='Envoltorio opcional que recibe el evaluador y mide cada proceso')
a=p.parse_args();seeds=json.loads(Path(a.seeds_json).read_text(encoding='utf-8'))
if not isinstance(seeds,list) or len(seeds)!=50 or any(type(s) is not int or s<0 for s in seeds) or len(set(seeds))!=50:
 raise ValueError('Se necesitan 50 semillas enteras distintas')
ck=Path(a.checkpoint).resolve();script=Path(a.script).resolve();out=Path(a.out).resolve();out.mkdir(parents=True,exist_ok=True)
with ck.open('rb') as f:ck_sha=hashlib.file_digest(f,'sha256').hexdigest()
for shape,goal,instruction in CASES:
 result=out/f'{shape}-{goal}.json'
 if result.exists():
  data=json.loads(result.read_text(encoding='utf-8'));c=data['contract'];records=data['records']
  expected={'checkpoint_sha256':ck_sha,'instruction':instruction,'goal':goal,'second_goal':None,
            'instruction_protocol':'fixed_for_episode','chunk_transition':'finish_pending_before_replanning',
            'episodes':50,'device_type':a.device,'max_steps':None,'trace_version':2,
            'shape':shape,'evaluation_seeds':seeds}
  if (any(k not in c or c[k]!=v for k,v in expected.items()) or
      [r['seed'] for r in records]!=seeds or data['successes']!=sum(r['success'] for r in records)):
   raise ValueError(f'Resultado incompatible: {result}')
  print('Reutilizado',result.name,flush=True);continue
 prefix=[sys.executable,'-u',str(Path(a.wrapper).resolve()),str(script)] if a.wrapper else [sys.executable,'-u',str(script)]
 cmd=prefix+['eval','--out',str(ck),'--result',str(result),'--device',a.device,
      '--episodes','50','--seeds-json',str(Path(a.seeds_json).resolve()),'--shape',shape,'--goal',goal,'--instruction',instruction]
 print('Iniciado',result.name,flush=True)
 with Path(str(result)+'.log').open('a',encoding='utf-8') as log:subprocess.run(cmd,stdout=log,stderr=subprocess.STDOUT,env=os.environ,check=True)
 if not result.exists():print('Pausa segura',result.name,flush=True);sys.exit(0)
 print('Finalizado',result.name,flush=True)
