"""Measure isolated certificate generation and checking, staging only complete results."""
import argparse,json,shutil,subprocess,sys,time
from pathlib import Path
import psutil
HERE=Path(__file__).resolve().parent
if __name__=='__main__':
    # The generated JSON can exceed the Windows pipe buffer. Workers write to temporary files.
    import tempfile
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('output',type=Path,help='new output directory for this benchmark')
    output_dir=parser.parse_args().output.resolve()
    output_dir.mkdir(exist_ok=False)
    stage=tempfile.TemporaryDirectory()
    wd=Path(stage.name)
    for name in ['garanties12.py','couverture10.py','reductions11.py','geometrie41.py','choix12.json']:
        shutil.copy2(HERE/name,wd/name)
    def worker(action,key):
        with tempfile.TemporaryFile() as output,tempfile.TemporaryFile() as errors:
            start=time.perf_counter();peak=0
            with subprocess.Popen([sys.executable,'-B','garanties12.py',action,key],cwd=wd,stdout=output,stderr=errors) as proc:
                monitor=psutil.Process(proc.pid)
                while proc.poll() is None:
                    try:peak=max(peak,monitor.memory_info().rss)
                    except psutil.NoSuchProcess:pass
                    if time.perf_counter()-start>60 or peak>512*1024**2:
                        proc.kill();proc.wait();return None,dict(cap=True,seconds=round(time.perf_counter()-start,4),sampled_peak_bytes=peak)
                    time.sleep(.02)
                if proc.returncode:
                    errors.seek(0);raise RuntimeError(errors.read().decode(errors='replace'))
            output.seek(0);return json.load(output),dict(seconds=round(time.perf_counter()-start,4),sampled_peak_bytes=peak)
    data={};times={}
    for k in 'ABC':
        v,report=worker('--generate',k);times[k]={'generation':report}
        if v is not None:data[k]=v
    (wd/'certificats12.json').write_text(json.dumps(data,indent=2)+'\n',encoding='utf8')
    for k in data:
        for method in ('sat','special'):
            v,t=worker('--'+method,k);times[k][method]={**t,'answer':v}
    (wd/'mesures-garanties12.json').write_text(json.dumps(times,indent=2)+'\n',encoding='utf8')
    for name in ['mesures-garanties12.json','certificats12.json']:
        shutil.copy2(wd/name,output_dir/name)
    stage.cleanup()
    print(json.dumps(times,indent=2))
