"""Run every fixed first-stage memory-control arm with at most two workers."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
root=Path(__file__).resolve().parent
python='/workspace/cadence-robot-arena/.venv/bin/python'
env={**os.environ,'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','MKL_NUM_THREADS':'1'}
jobs=[(case,arm) for case in ['tumbler-103','mantis-202'] for arm in ['control','memory']]
manifest={'started_utc':datetime.now(timezone.utc).isoformat(),'jobs':jobs,'max_workers':2,'hashes':{name:hashlib.sha256((root/name).read_bytes()).hexdigest() for name in ['compare.py','protocol.json','sources.json','launch.py']}}
(root/'launch.json').write_text(json.dumps(manifest,indent=2)+'\n')
def run(job):
 case,arm=job
 command=[python,str(root/'compare.py'),'--case',case,'--arm',arm]
 with (root/f'{case}-{arm}.log').open('w') as stream:
  result=subprocess.run(command,env=env,stdout=stream,stderr=subprocess.STDOUT)
 out={'case':case,'arm':arm,'returncode':result.returncode,'finished_utc':datetime.now(timezone.utc).isoformat()}
 print(json.dumps(out),flush=True)
 return out
with ThreadPoolExecutor(max_workers=2) as pool:
 results=list(pool.map(run,jobs))
(root/'complete.json').write_text(json.dumps(results,indent=2)+'\n')
sys.exit(any(row['returncode'] for row in results))
