"""Verify a downloaded bundle, or stage an explicitly requested fresh inference run."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys

ROOT=Path(__file__).resolve().parent

def main(args):
 manifest=json.loads((ROOT/'MANIFEST.json').read_text(encoding='utf-8'))
 for relative,record in manifest.items():
  path=ROOT/relative
  if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest()!=record['sha256']:raise SystemExit('File verification failed: '+relative)
 print(f'PASS: {len(manifest)} file hashes verified.')
 from verify_evidence import Audit
 audit=Audit()
 for seal in (ROOT/'protocols').glob('*/seal.json'):audit.seal(seal)
 if audit.errors:raise SystemExit('Prospective source verification failed: '+str(audit.errors))
 print(f'PASS: {audit.checks} prospective source checks.')
 if not args.fresh_phase:
  if not (ROOT/'runs').is_dir():
   print('Study materials verified. Download the separate evidence bundles to recheck raw observations; see README.md for analysis commands.')
   return
  for run in (ROOT/'runs').iterdir():
   if run.is_dir():subprocess.run([sys.executable,str(ROOT/'verify_evidence.py'),str(run)],check=True)
  return
 phase=ROOT/'protocols'/args.fresh_phase
 if not phase.is_dir():raise SystemExit('Phase not included in this bundle.')
 if not args.output:raise SystemExit('--output is required for fresh inference staging.')
 target=Path(args.output).resolve()
 target.mkdir(parents=True,exist_ok=False)
 for source in (phase/'source').iterdir():
  if source.is_file():shutil.copy2(source,target/source.name)
 shutil.copytree(phase,target/'protocols'/args.fresh_phase)
 print('Staged at '+str(target)+'. Install the pinned requirements and ensure the recorded CLIs are authenticated.')
 if args.execute:
  print('Starting NEW provider inference. Fresh responses may differ and consume account usage.')
  plan=json.loads((phase/'plan.json').read_text(encoding='utf-8'))
  command=[sys.executable,str(target/'runtime_followup.py'),'run'] if plan.get('supervised_runtime') else [sys.executable,str(target/'experiment.py'),'run','--phase',args.fresh_phase]
  subprocess.run(command,cwd=target,check=True)

if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('--fresh-phase');ap.add_argument('--output');ap.add_argument('--execute',action='store_true');main(ap.parse_args())
