"""Run real server/MCP Stop comparisons. All paths must refer to synthetic proof state.
Usage: python3 app-compare.py ROOT BASE_CHECKOUT HEAD_CHECKOUT BASE_HOME HEAD_HOME BASE_PROJECT HEAD_PROJECT
ROOT contains driver.mjs, stop.mjs and trace.cjs. Seed each home first; see README.
"""
import sys,os,pathlib,subprocess,time,urllib.request,json,datetime,signal,sqlite3,statistics
root,base,head,basehome,headhome,baseproject,headproject=sys.argv[1:]
root=pathlib.Path(root);out=root/datetime.datetime.now(datetime.timezone.utc).strftime('real-app-%Y%m%dT%H%M%SZ');out.mkdir()
configs={'base':(base,basehome,baseproject,38550),'head':(head,headhome,headproject,38549)}
result={'environment':'Linux x86_64; Node v26.13.1; same machine, sequential measurements','method':'Real source server, MCP t3_thread_interrupt(stop:true); SQLite read traced inside real worker; synthetic projection events applied through production service after startup recovery.','sides':{s:{'warm':[],'cold':[]} for s in configs}}
expected=None

def run_side(side,kind,round_index=0):
 global expected
 checkout,home,project,port=configs[side];name=f'{side}-{kind}-{round_index}';trace=out/(name+'.jsonl');log=open(out/(name+'-server.log'),'w')
 env={**os.environ,'T3CODE_DEV_SEED':'0','PERF_CAPTURE':str(trace),'NODE_OPTIONS':'--require='+str(root/'trace.cjs')}
 db=pathlib.Path(home)/'userdata/statev2.sqlite'
 server=subprocess.Popen(['node','src/bin.ts','serve','--base-dir',home,'--port',str(port),'--dev-url',f'http://127.0.0.1:{port+20000}','--no-browser'],cwd=checkout+'/apps/server',env=env,stdout=log,stderr=log)
 try:
  # Readiness checks are for app startup, outside measured actions.
  deadline=time.monotonic()+45
  while True:
   if server.poll() is not None:raise RuntimeError(name+' server exited')
   try:
    with urllib.request.urlopen(f'http://127.0.0.1:{port}/.well-known/t3/environment',timeout=1) as r:
     if r.status==200:break
   except Exception:
    if time.monotonic()>deadline:raise RuntimeError(name+' readiness timeout')
    time.sleep(.1)
  seeded=subprocess.run(['node',str(root/'driver.mjs'),checkout,'parents',str(db),str(out/(name+'-fixture.json'))],env={**os.environ,'PROOF_PROJECT':project},capture_output=True,text=True)
  if seeded.returncode:raise RuntimeError(seeded.stderr)
  # The fixture has to follow startup: recovery correctly closes stale native tasks at boot.
  with sqlite3.connect(f'file:{db}?mode=ro',uri=True) as c:
   before=c.execute("SELECT status,count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='thread:perf-proof' GROUP BY status").fetchall()
  if dict(before)!={'completed':30991,'pending':3,'running':3,'waiting':3}:raise RuntimeError('incorrect child fixture')
  indices=range(16) if kind=='warm' else [0]
  for i in indices:
   if kind=='cold':
    f=os.open(db,os.O_RDONLY);os.posix_fadvise(f,0,0,os.POSIX_FADV_DONTNEED);os.close(f)
   previous=len(trace.read_text().splitlines()) if trace.exists() else 0
   action=subprocess.run(['node',str(root/'stop.mjs'),checkout,home,str(i)],capture_output=True,text=True)
   (out/(name+f'-action-{i}.log')).write_text(action.stdout+action.stderr)
   if action.returncode:raise RuntimeError(name+' MCP call failed: '+action.stderr)
   value=json.loads(action.stdout)
   reads=[json.loads(x) for x in trace.read_text().splitlines()[previous:]] if trace.exists() else []
   if len(reads)!=1:raise RuntimeError(f'{name} expected one nine-row read, got {len(reads)}')
   read=reads[0]
   if expected is not None and expected!=read['digest']:raise RuntimeError('returned payload/order changed')
   expected=read['digest']
   with sqlite3.connect(f'file:{db}?mode=ro',uri=True) as c:
    state=c.execute('SELECT status FROM orchestration_v2_projection_subagents WHERE thread_id=?',('thread:parent:'+str(i),)).fetchone()[0]
    plan=[r[3] for r in c.execute('EXPLAIN QUERY PLAN '+read['query'],read['params'])]
   if state!='interrupted':raise RuntimeError('Stop did not interrupt the native task: '+state)
   sample={**read,'actionMs':value['actionMs'],'mcpResult':value['value'],'taskAfterStop':state,'plan':plan}
   if kind!='warm' or i>0:result['sides'][side][kind].append(sample)
   print(side,kind,i,'read',round(read['ms'],3),'action',round(value['actionMs'],3),flush=True)
 finally:
  server.send_signal(signal.SIGINT)
  try:server.wait(timeout=15)
  except subprocess.TimeoutExpired:server.kill();server.wait(timeout=5)
  log.close()

for side in ['base','head']:run_side(side,'warm')
for i in range(7):
 for side in (['base','head'] if i%2==0 else ['head','base']):run_side(side,'cold',i+1)
for side,data in result['sides'].items():
 data['sha']=subprocess.check_output(['git','-C',configs[side][0],'rev-parse','HEAD'],text=True).strip()
 data['summary']={}
 for kind in ['warm','cold']:
  data['summary'][kind]={}
  for metric in ['ms','actionMs']:
   values=[r[metric] for r in data[kind]]
   data['summary'][kind][metric]={'samples':values,'median':statistics.median(values),'min':min(values),'max':max(values),'spread':max(values)-min(values)}
(out/'real-app-results.json').write_text(json.dumps(result,indent=2)+'\n')
print(out,flush=True)
