import os, sys, subprocess, time, pathlib, json, statistics, re, platform
root = pathlib.Path(os.environ['MAC_WORK'])
out = root / ('measurement-' + time.strftime('%Y%m%d-%H%M%S'))
out.mkdir()
print('macOS', platform.mac_ver()[0], platform.machine(), flush=True)
print('Wall clock includes vp startup; five samples, alternating order; Vite/Vitest disk caches moved aside before every run. OS filesystem cache is not purged.', flush=True)
results=[]
for sample in range(1,6):
 for side in (['base','head'] if sample%2 else ['head','base']):
  work=root/side
  for label, file in [('shared','packages/shared/src/String.test.ts'),('web','apps/web/src/terminal-links.test.ts')]:
   # Preserve caches outside the checkout, leaving the next invocation cold.
   caches=[]
   for current, dirs, files in os.walk(work, followlinks=False):
    for name in list(dirs):
     p=pathlib.Path(current)/name
     if name in ('.vite','.vitest','.vite-temp') and not p.is_symlink():
      caches.append(p); dirs.remove(name)
     elif name in ('.git','.pnpm') or p.is_symlink(): dirs.remove(name)
   stash=out/f'cache-{sample}-{side}-{label}'; stash.mkdir()
   for n,p in enumerate(caches): p.rename(stash/str(n))
   cmd=['vp','test','run',file]
   env=dict(os.environ, NO_COLOR='1', FORCE_COLOR='0', CI='1')
   start=time.perf_counter()
   proc=subprocess.run(cmd,cwd=work,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
   elapsed=time.perf_counter()-start
   output=re.sub(r'\x1b\[[0-9;]*[A-Za-z]','',proc.stdout).replace(str(work),'<checkout>').replace(str(root),'<workspace>')
   output=re.sub(r'/Users/[^/\s]+','<home>',output)
   record=dict(sample=sample,side=side,command=' '.join(cmd),seconds=round(elapsed,3),exit=proc.returncode,output=output)
   results.append(record)
   print(f'\n=== {side} {label} sample {sample}: {elapsed:.3f} s; exit {proc.returncode} ===\n{output}',flush=True)
   (out/'results.json').write_text(json.dumps(results,indent=2))
print('\nSUMMARY',flush=True)
for side in ['base','head']:
 for label in ['shared','web']:
  rows=[r for r in results if r['side']==side and label in r['command']]
  times=[r['seconds'] for r in rows]
  print(side,label,'samples',times,'median',statistics.median(times),'range',min(times),max(times),'spread',round(max(times)-min(times),3),flush=True)
