"""Empaqueta el contraste reservado; restaura y recalcula sin incluir pesos."""
import argparse,hashlib,json,subprocess,sys,zipfile
from pathlib import Path
def digest(b):return hashlib.sha256(b).hexdigest()
def main():
 p=argparse.ArgumentParser()
 for n in ('grpo-eval','base-eval','grpo-run','star-run','star-audit','contract','comparison','model-path','output','restore'):p.add_argument('--'+n,required=True)
 a=p.parse_args();out=Path(a.output);restore=Path(a.restore)
 if out.exists() or restore.exists():raise FileExistsError('Destinos ya existentes')
 expected=json.loads(Path(a.comparison).read_text(encoding='utf8'));files={}
 def add(name,path,expected_sha=None):
  blob=Path(path).read_bytes();h=digest(blob)
  if expected_sha and expected_sha!=h:raise ValueError('Huella incorrecta: '+name)
  if any(x.lower() in blob.decode('utf8').lower() for x in ('/mnt/c/Users/','C:\\\\Users\\\\','/home/Guayamose/','site-packages')):raise ValueError('Ruta local: '+name)
  files[name]=blob
 for k,root in enumerate((Path(a.grpo_eval),Path(a.base_eval))):
  role=('grpo-eval','base-eval')[k];add(role+'/protocol.json',root/'protocol.json',expected[('grpo_protocol_sha256','star_protocol_sha256')[k]])
  hashes=expected['group_and_test_sha256'][k];idx=0
  for i in range(200):
   for g in range(32):
    name=f'group-{i:04d}-{g:02d}.json';add(role+'/'+name,root/name,hashes[idx]);idx+=1
   name=f'test-{i:04d}.json';add(role+'/'+name,root/name,hashes[idx]);idx+=1
  if idx!=len(hashes):raise ValueError('Inventario incompleto')
 plan=json.loads(Path(a.contract).read_text(encoding='utf8'))
 for field,name in [('grpo_protocol_sha256','protocol.json'),('grpo_rollouts_sha256','rollouts.jsonl'),('grpo_profile_sha256','profile.jsonl'),('grpo_runs_sha256','runs.jsonl')]:add('grpo-run/'+name,Path(a.grpo_run)/name,plan[field])
 add('contract.json',a.contract,expected['planned_contract_sha256']);add('star-audit.json',a.star_audit,expected['star_audit_sha256']);add('comparison-original.json',a.comparison)
 manifest={'scope':'Evaluación reservada emparejada y contratos; no contiene pesos. La campaña STaR se distribuye en traces.zip separado.','members_sha256':{k:digest(v) for k,v in files.items()}}
 files['manifest.json']=json.dumps(manifest,ensure_ascii=False,indent=2).encode('utf8')
 out.parent.mkdir(parents=True,exist_ok=True);tmp=out.with_suffix(out.suffix+'.partial')
 if tmp.exists():raise FileExistsError('Temporal anterior')
 with zipfile.ZipFile(tmp,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:
  for name,blob in files.items():z.writestr(name,blob)
 restore.mkdir(parents=True)
 with zipfile.ZipFile(tmp) as z:
  if z.testzip() or set(z.namelist())!=set(files):raise ValueError('ZIP corrupto')
  z.extractall(restore)
 for name,blob in files.items():
  if digest((restore/name).read_bytes())!=digest(blob):raise ValueError('Restauración incorrecta')
 cmd=[sys.executable,str(Path(__file__).with_name('compare_star_budget_grpo_vllm.py')),'--grpo-eval',str(restore/'grpo-eval'),'--star-eval',str(restore/'base-eval'),'--grpo-run',str(restore/'grpo-run'),'--star-run',a.star_run,'--star-audit',str(restore/'star-audit.json'),'--planned-contract',str(restore/'contract.json'),'--model-path',a.model_path,'--output',str(restore/'comparison-restored.json')]
 subprocess.run(cmd,check=True)
 if json.loads((restore/'comparison-restored.json').read_text(encoding='utf8'))!=expected:raise ValueError('Comparación restaurada difiere')
 tmp.replace(out);print('Evaluaciones restauradas y comparador completo repetido:',digest(out.read_bytes()),out.stat().st_size)
if __name__=='__main__':main()
