# Run after vp i in both checkouts. Uses the repository benchmark unchanged.
# Trace files rotate: preserved server.trace.ndjson is only the final segment.
import os, pathlib, subprocess, time, shutil, datetime, argparse
parser=argparse.ArgumentParser()
parser.add_argument('--head',required=True,type=pathlib.Path)
parser.add_argument('--base',required=True,type=pathlib.Path)
parser.add_argument('--out',required=True,type=pathlib.Path)
a=parser.parse_args()
root=a.out.resolve(); root.mkdir(parents=True,exist_ok=True)
head=a.head.resolve(); base=a.base.resolve()
runroot=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
runroot.mkdir()
for i,side in enumerate(['base','head','head','base','base','head']):
    out=runroot/f'{i+1}-{side}'; out.mkdir(); temp=out/'tmp';temp.mkdir()
    env={**os.environ,'TMPDIR':str(temp),'T3CODE_DEV_SEED':'0'}
    cmd=['node','scripts/metrics/server/server-metrics.ts','run','--only','streaming','--checkout',str(base if side=='base' else head),'--out',str(out/'metrics.json')]
    with (out/'console.txt').open('w') as log:
        p=subprocess.Popen(cmd,cwd=head,env=env,stdout=log,stderr=subprocess.STDOUT)
        while p.poll() is None:
            for f in temp.rglob('server.trace.ndjson'):
                try: shutil.copyfile(f,out/'server.trace.ndjson')
                except FileNotFoundError: pass
            time.sleep(.25)
    print(out.name, 'exit',p.returncode,flush=True)
    if p.returncode: print((out/'console.txt').read_text()[-6000:],flush=True); break
print('OUTPUT',runroot,flush=True)
