import json,os,subprocess
from pathlib import Path
root=Path('artifacts/exchange-frontier-20260911')
out=root/'hardware';out.mkdir(exist_ok=True)
cases=[('paired-9-auto','selected.json',3,[]),
       ('phase16-balanced128','selected.json',7,['--exchange-stream-words','128','--exchange-replay-balance-streams']),
       ('phase47-balanced1024','selected.json',11,['--exchange-stream-words','1024','--exchange-replay-balance-streams']),
       ('phase49-stream256','selected.json',12,['--exchange-stream-words','256']),
       ('phase49-balanced256','selected.json',12,['--exchange-stream-words','256','--exchange-replay-balance-streams']),
       ('phase42-auto','selected.json',10,[])]
rows=json.loads((root/'ordinary-phase9-plots/results.json').read_text())
best=min((r for r in rows if r['family'] in ['stream','balanced']),key=lambda r:(r['cycles'],r['maximum_row_bytes']))
family,words=best['configuration'].split('-')
flags=['--exchange-stream-words',words]
if family=='balanced':flags+=['--exchange-replay-balance-streams']
cases.append(('ordinary-9-'+best['configuration'],'ordinary-phase9.json',0,flags))
prior=json.loads((out/'results.json').read_text()) if (out/'results.json').exists() else []
results=[r for r in prior if r['exit_code']==0]
for name,snapshot,index,flags in cases:
 if any(r['name']==name for r in results):continue
 log=out/(name+'.log')
 if log.exists():log.rename(out/(name+'.initial.log'))
 command=['target/release/ipu-trivial-test',os.environ['IPU_CONFIG'],'--runtime-source','device/static_runtime.S','--sdk',os.environ['POPLAR_SDK_ENABLED'],'--replay-exchange-schedule',str(root/snapshot),'--exchange-replay-phase',str(index),'--device-lock','artifacts/layout-sweep/device.lock','--package',str(out/(name+'.ipuexe')),*flags]
 print(name,flush=True)
 with (out/(name+'.log')).open('w') as log:
  result=subprocess.run(command,stdout=log,stderr=subprocess.STDOUT,env={**os.environ,'RAYON_NUM_THREADS':'8','RUST_LOG':'info'})
 results.append({'name':name,'exit_code':result.returncode,'command':command})
 (out/'results.json').write_text(json.dumps(results,indent=2)+'\n')
