"""Publica y restaura las trazas presupuestadas, sin pesos ni rutas locales."""
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():
 p=argparse.ArgumentParser()
 for name in ('run','audit','model-path','output','restore'): p.add_argument('--'+name,required=True)
 a=p.parse_args(); root=Path(a.run); out=Path(a.output); restore=Path(a.restore)
 if out.exists() or restore.exists(): raise FileExistsError('Elige destinos nuevos')
 audit=json.loads(Path(a.audit).read_text(encoding='utf8'))
 if audit['protocol_sha256']!=digest(root/'protocol.json') or audit['auditor_sha256']!=digest(Path(__file__).with_name('audit_star_budget.py')): raise ValueError('Auditoría cambiada')
 files={'run/protocol.json':(root/'protocol.json').read_bytes(),'audit-original.json':Path(a.audit).read_bytes()}
 for name,h in audit['group_sha256'].items():
  blob=(root/name).read_bytes()
  if sha(blob)!=h: raise ValueError('Grupo alterado '+name)
  files['run/'+name]=blob
 for r,item in enumerate(audit['rounds']):
  for name,key in ((f'training-{r}.json','training_sha256'),(f'policy-{r+1}.json','policy_marker_sha256')):
   blob=(root/name).read_bytes()
   if sha(blob)!=item[key]: raise ValueError('Marcador alterado '+name)
   files['run/'+name]=blob
 for item in audit['phase_timings']:
  name='phase-timings/'+item['file'];blob=(root/name).read_bytes()
  if sha(blob)!=item['sha256']: raise ValueError('Fase alterada '+name)
  files['run/'+name]=blob
 for name,blob in files.items():
  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 en '+name)
 manifest={'scope':'7200 muestras train persistidas y 6400 test internos, protocolos y auditoría; sin pesos ni logs.','members_sha256':{k:sha(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);part=out.with_suffix(out.suffix+'.partial')
 if part.exists():raise FileExistsError('Temporal anterior')
 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('Archivo corrupto')
  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_star_budget.py')),'--run',str(restore/'run'),'--model-path',a.model_path,'--output',str(restore/'restored-audit.json')],check=True)
 part.replace(out);print('Archivo restaurado y reauditado:',out,'SHA256',digest(out),'bytes',out.stat().st_size)
if __name__=='__main__':main()
