#!/usr/bin/env python3
"""Real T3 server/CLI proof. Usage: python3 measure.py CHECKOUT OUTPUT_ROOT SIDE
Creates fresh state; never copies a database. Requires node, installed checkout dependencies.
Raw server logs remain private; public JSON contains only synthetic outcomes and trace timings.
"""
import os,sys,json,subprocess,time,pathlib,socket,sqlite3,statistics,platform,signal
checkout=pathlib.Path(sys.argv[1]).resolve(); root=pathlib.Path(sys.argv[2]).resolve(); side=sys.argv[3]
out=root/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); out.mkdir(parents=True)
home=out/'home'; log=out/'server-private.log'; cli=checkout/'apps/server/src/bin.ts'
env=dict(os.environ,T3CODE_DEV_SEED='0',T3CODE_TRACE_MIN_LEVEL='Debug',T3CODE_TRACE_MAX_BYTES='2000000000',T3CODE_TRACE_MAX_FILES='10',T3CODE_TELEMETRY_ENABLED='false')
for k in ['T3CODE_HOME','T3CODE_PORT','T3CODE_HOST','VITE_HTTP_URL','VITE_WS_URL']: env.pop(k,None)
def command(args):
 p=subprocess.run(['node',str(cli),*args,'--base-dir',str(home)],cwd=checkout,env=env,text=True,capture_output=True,timeout=120)
 if p.returncode: raise RuntimeError(f'CLI {args[0:2]} failed: {p.stdout} {p.stderr}')
 return p.stdout.strip()
def children(pid):
 result=[]
 for proc in pathlib.Path('/proc').iterdir():
  if not proc.name.isdigit(): continue
  try:
   if int((proc/'stat').read_text().split(') ')[1].split()[1])==pid:
    result += children(int(proc.name))+[int(proc.name)]
  except (FileNotFoundError,ProcessLookupError,PermissionError): pass
 return result
f=log.open('w'); server=subprocess.Popen(['node','scripts/dev-runner.ts','dev:server','--home-dir',str(home),'--no-seed'],cwd=checkout,env=env,stdout=f,stderr=subprocess.STDOUT)
try:
 deadline=time.monotonic()+180
 while 'Listening on http://' not in log.read_text():
  if server.poll() is not None or time.monotonic()>deadline: raise RuntimeError('server failed to start; inspect private log')
  time.sleep(.25)
 # The dev provider advertises a temporary default model during its background probe.
 deadline=time.monotonic()+120
 while True:
  try:
   models=json.loads((home/'caches/devReplay.json').read_text()).get('models',[])
   if any(m['slug']=='multi-turn' for m in models): break
  except FileNotFoundError: pass
  if time.monotonic()>deadline: raise RuntimeError('Replay model discovery did not finish')
  time.sleep(.25)
 command(['project','add',str(checkout),'--title','Synthetic handoff performance proof'])
 outcomes=[]
 for n in range(1,451):
  args=['thread','start',str(checkout),'turn 1','--provider','devReplay','--model','multi-turn'] if n==1 else ['thread','send',thread,'turn '+str(n)]
  result=json.loads(command(args+['--wait','--json'])); thread=result['threadId']
  outcomes.append({'turn':n,'status':result['status'],'reply':result.get('reply'),'error':result.get('error')})
  if result['status']!='completed' or result.get('error'): raise RuntimeError('turn failed')
  if n%25==0: print(side, 'completed', n, 'turns',flush=True)
 db=sqlite3.connect('file:'+str(home/'userdata/statev2.sqlite')+'?mode=ro',uri=True)
 checks={'runs':db.execute('select count(*) from orchestration_v2_projection_runs').fetchone()[0], 'userMessages':db.execute("select count(*) from orchestration_v2_projection_messages where role='user'").fetchone()[0], 'handoff':db.execute("select json_extract(payload_json,'$.handoff') from orchestration_v2_projection_threads where thread_id=?",(thread,)).fetchone()[0], 'runStatusCounts':dict(db.execute("select status,count(*) from orchestration_v2_projection_runs group by status"))}
 db.close()
 # Allow the configured one-second trace batch to flush; this is not a timing sample.
 time.sleep(2)
finally:
 descendants=children(server.pid)
 server.send_signal(signal.SIGINT)
 for pid in descendants:
  try: os.kill(pid,signal.SIGTERM)
  except ProcessLookupError: pass
 try: server.wait(timeout=15)
 except subprocess.TimeoutExpired: server.kill();server.wait()
 f.close()
trace=home/'userdata/logs/server.trace.ndjson'; pending={}; settles=[]
for line in trace.open():
 try: span=json.loads(line)
 except json.JSONDecodeError: continue
 if span.get('type')!='effect-span': continue
 key=(span['traceId'],span['spanId']); tables=pending.pop(key,set())
 sql=span.get('attributes',{}).get('db.query.text','')
 import re
 tables.update(re.findall(r'orchestration_v2_projection_[a-z_]+',sql))
 if span['name']=='ThreadHandoff.settle':
  settles.append({'durationMs':span['durationMs'],'tables':sorted(tables),'success':span.get('exit',{}).get('_tag')=='Success','startTimeUnixNano':span['startTimeUnixNano']})
 if span.get('parentSpanId'): pending.setdefault((span['traceId'],span['parentSpanId']),set()).update(tables)
settles.sort(key=lambda s:int(s['startTimeUnixNano']))
for s in settles: s.pop('startTimeUnixNano')
def stats(values):
 q=statistics.quantiles(values,n=4)
 return {'n':len(values),'medianMs':statistics.median(values),'minMs':min(values),'maxMs':max(values),'p25Ms':q[0],'p75Ms':q[2]}
# Exactly two terminal run.updated events / settle calls per completed replay turn.
assert len(settles)==900,(len(settles),checks)
last=settles[800:900]; batches=[stats([s['durationMs'] for s in last[i:i+20]]) for i in range(0,100,20)]
report={'side':side,'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'environment':{'os':platform.system(),'architecture':platform.machine(),'node':subprocess.check_output(['node','--version'],text=True).strip(),'provider':'Replay (dev)','model':'multi-turn','freshDatabase':True,'traceLevel':'Debug','surface':'real server / official CLI'},'steps':'Fresh server and database; project add; thread start turn 1 --provider devReplay --model multi-turn --wait; thread send turn N --wait for turns 2..450. No handoff requested. Measure settle spans for turns 401..450 as five consecutive batches of 10 turns (20 settle calls each).','checks':checks,'outcomes':outcomes,'settleCalls':len(settles),'first41Turns':stats([s['durationMs'] for s in settles[:82]]),'last50Turns':stats([s['durationMs'] for s in last]),'batches':batches,'batchMedianRangeMs':[min(b['medianMs'] for b in batches),max(b['medianMs'] for b in batches)],'last50CallsReadingHistory':sum(any(t.endswith('_runs') or t.endswith('_messages') for t in s['tables']) for s in last),'last50Tables':sorted(set(t for s in last for t in s['tables'])),'settles':settles}
(out/'measurement.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k not in ['outcomes','settles']},indent=2),flush=True)
print('REPORT',out/'measurement.json',flush=True)
