"""Empaqueta las 600 trazas Qwen3 y reaudita una restauración, sin pesos."""
import argparse,hashlib,json,subprocess,sys,zipfile
from pathlib import Path

def sha(data):return hashlib.sha256(data).hexdigest()
def digest(path):return sha(Path(path).read_bytes())
def main():
 ap=argparse.ArgumentParser();ap.add_argument('--run',required=True);ap.add_argument('--audit',required=True);ap.add_argument('--data',required=True);ap.add_argument('--model-path',required=True);ap.add_argument('--output',required=True);ap.add_argument('--restore',required=True);args=ap.parse_args()
 root=Path(args.run);audit=json.loads(Path(args.audit).read_text(encoding='utf8'));out=Path(args.output);restore=Path(args.restore)
 if out.exists() or restore.exists():raise FileExistsError('Usa destinos nuevos')
 if (audit.get('rows')!=600 or audit.get('protocol_sha256')!=digest(root/'protocol.json') or audit.get('summary_sha256')!=digest(root/'summary.json') or audit.get('source_sha256')!=digest(args.data) or audit.get('auditor_sha256')!=digest(Path(__file__).with_name('audit_hybrid_modes.py'))):raise ValueError('Auditoría incompatible')
 files={'run/protocol.json':(root/'protocol.json').read_bytes(),'run/summary.json':(root/'summary.json').read_bytes(),'audit-original.json':Path(args.audit).read_bytes()}
 for mode in ('sin_pensamiento','pensamiento_256','pensamiento_1024'):
  for i in range(200):
   name=f'{i:03d}-{mode}.json';blob=(root/name).read_bytes()
   if audit['records_sha256'].get(name)!=sha(blob):raise ValueError('Traza alterada')
   files['run/'+name]=blob
 banned=('/mnt/c/Users/','C:\\Users\\','/home/Guayamose/','site-packages')
 for name,blob in files.items():
  if any(x.lower() in blob.decode('utf8').lower() for x in banned):raise ValueError('Ruta local en '+name)
 manifest={'scope':'600 trazas, tokens, protocolo y auditoría; sin pesos base ni logs.',
           'model':'Qwen/Qwen3-1.7B','revision':'70d244cc86ccca08cf5af4e1e306ecf908b1ad5e',
           'members_sha256':{name:sha(blob) for name,blob in files.items()}}
 files['manifest.json']=json.dumps(manifest,ensure_ascii=False,indent=2).encode('utf8')
 out.parent.mkdir(parents=True,exist_ok=True);part=out.with_suffix(out.suffix+'.partial')
 if part.exists():raise FileExistsError('Temporal previo')
 with zipfile.ZipFile(part,'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(part) as z:
  if z.testzip() or set(z.namelist())!=set(files):raise ValueError('ZIP alterado')
  z.extractall(restore)
 for name,blob in files.items():
  if digest(restore/name)!=sha(blob):raise ValueError('Restauración alterada')
 subprocess.run([sys.executable,str(Path(__file__).with_name('audit_hybrid_modes.py')),'--run',str(restore/'run'),'--data',args.data,
                 '--model-path',args.model_path,'--output',str(restore/'restored-audit.json')],check=True)
 part.replace(out);print('Qwen3 portable restaurado y reauditado:',out,'SHA256',digest(out),'bytes',out.stat().st_size)
if __name__=='__main__':main()
