import os,sys,time,json,subprocess,statistics,pathlib,signal,datetime
ROOT=pathlib.Path(__file__).resolve().parent
RUN=ROOT/datetime.datetime.now(datetime.timezone.utc).strftime('run-%Y%m%d-%H%M%S'); RUN.mkdir()
# Usage: python3 measure.py BASE_CHECKOUT HEAD_CHECKOUT
# Fresh state, same machine, real T3 server and real Claude Haiku on both commits.
# Output deliberately excludes machine names, filesystem paths, auth and provider transcript.
def run_side(side,checkout,port):
    out=RUN/side; out.mkdir(); home=out/'home'; project=out/'project'; project.mkdir()
    subprocess.run(['git','init','-q',str(project)],check=True)
    jobs=project/'jobs.sh'
    jobs.write_text('''#!/bin/bash
set -e
for ((b=0;b<$1;b++)); do
  for ((j=0;j<$2;j++)); do sleep 1.5 & done
  wait
done
printf 'JOBS_DONE %s\\n' "$(($1*$2))"
''')
    env=os.environ.copy(); env.pop('XDG_RUNTIME_DIR',None); env['T3CODE_DEV_SEED']='0'
    serverlog=open(out/'private-server.log','w')
    server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--port',str(port),'--host','127.0.0.1','--base-dir',str(home),'--no-browser'],cwd=checkout,env=env,stdout=serverlog,stderr=subprocess.STDOUT)
    def cli(*args,timeout=600):
        p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,env=env,text=True,capture_output=True,timeout=timeout)
        if p.returncode: raise RuntimeError('CLI failed: '+p.stdout[-500:]+p.stderr[-500:])
        return p.stdout
    def children(pid):
        return [int(p.name) for p in pathlib.Path('/proc').iterdir() if p.name.isdigit() and getppid(p)==pid]
    def getpidcli():
        for pid in children(server.pid):
            try:
                if b'claude' in pathlib.Path(f'/proc/{pid}/cmdline').read_bytes():return pid
            except FileNotFoundError:pass
        raise RuntimeError('Claude not a direct child')
    trace=home/'userdata/logs/server.trace.ndjson'
    def cpu():
        a=pathlib.Path(f'/proc/{server.pid}/stat').read_text().split(') ')[1].split()
        return (int(a[11])+int(a[12]))/os.sysconf('SC_CLK_TCK')
    def window(stage,index):
        start=time.time_ns(); c=cpu(); time.sleep(30); end=time.time_ns(); dc=cpu()-c
        spans=[]
        for line in trace.read_text().splitlines():
            try:r=json.loads(line)
            except:continue
            if r.get('name')=='ClaudeAgentSdkQueryRunner.trackDescendants' and start<=int(r['startTimeUnixNano'])<end:spans.append(r['durationMs'])
        if len(spans)<20:raise RuntimeError(f'Not enough polls: {len(spans)}')
        spans.sort()
        r={'stage':stage,'window':index,'polls':len(spans),'p50_ms':round(statistics.median(spans),3),'p90_ms':round(spans[int(len(spans)*.9)],3),'cpu_ms_per_s':round(dc/((end-start)/1e9)*1000,3),'samples_ms':spans}
        print(side,json.dumps({k:v for k,v in r.items() if k!='samples_ms'}),flush=True)
        return r
    result={'side':side,'sha':subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'platform':'Linux x86_64','runtime':subprocess.check_output(['node','--version'],cwd=checkout,text=True).strip(),'model':'claude-haiku-5-5','agent_scope':False,'windows':[]}
    try:
        for _ in range(120):
            if 'T3 Code server is ready.' in (out/'private-server.log').read_text():break
            if server.poll() is not None:raise RuntimeError('Server exited')
            time.sleep(.5)
        cli('project','add',str(project),'--title','Process poll evidence')
        reply=json.loads(cli('thread','start',str(project),'Reply OK','--provider','claudeAgent','--model','claude-haiku-5-5','--wait','--json'))
        thread=reply['threadId']; result['initial_reply']=reply.get('reply'); result['initial_status']=reply['status']
        claudepid=getpidcli(); result['direct_child_confirmed']=True
        for i in range(1,4):result['windows'].append(window('baseline',i))
        for batches,size,total in [(20,250,5000),(60,1000,65000)]:
            reply=json.loads(cli('thread','send',thread,f'Run exactly bash jobs.sh {batches} {size} in the current directory using Bash. Do not delegate. Wait for it to finish, then reply only JOBS_DONE.','--wait','--json',timeout=900))
            result[f'jobs_{total}_status']=reply['status']
            # Allow final children to exit before measuring idle polling.
            time.sleep(5)
            for i in range(1,4):result['windows'].append(window(f'after_{total}_jobs',i))
            (out/'measurement.json').write_text(json.dumps(result,indent=2))
        survivor=project/'survivor.sh'
        survivor.write_text('''#!/bin/bash
setsid sleep 600 </dev/null >/dev/null 2>&1 &
echo $! > survivor.pid
sleep 4
echo SURVIVOR_READY
''')
        reply=json.loads(cli('thread','send',thread,'Run bash survivor.sh using Bash. Do not delegate. Reply only SURVIVOR_READY.','--wait','--json'))
        spid=int((project/'survivor.pid').read_text()); result['survivor_alive_before_cli_exit']=pathlib.Path(f'/proc/{spid}').exists()
        os.kill(claudepid,signal.SIGTERM)
        for _ in range(60):
            if not pathlib.Path(f'/proc/{spid}').exists():break
            # A zombie is ended; init may not immediately reap it in a container.
            if pathlib.Path(f'/proc/{spid}/stat').read_text().split(') ')[1].startswith('Z'):break
            time.sleep(.5)
        result['survivor_cleaned_after_cli_exit']=not pathlib.Path(f'/proc/{spid}').exists() or pathlib.Path(f'/proc/{spid}/stat').read_text().split(') ')[1].startswith('Z')
        if not result['survivor_cleaned_after_cli_exit']:os.kill(spid,signal.SIGKILL)
        result['live_process_table_rows']=len(subprocess.check_output(['ps','-A','-o','pid='],text=True).splitlines())
    finally:
        server.send_signal(signal.SIGINT)
        try:server.wait(timeout=30)
        except subprocess.TimeoutExpired:server.kill();server.wait()
        serverlog.close()
        (out/'measurement.json').write_text(json.dumps(result,indent=2))
    print('SIDE_DONE',side,flush=True)
    return result

def getppid(p):
    try:return int((p/'stat').read_text().split(') ')[1].split()[1])
    except (OSError,ValueError):return -1
results=[]
for side,checkout,port in [('before',sys.argv[1],19482),('after',sys.argv[2],19483)]:results.append(run_side(side,checkout,port))
(RUN/'comparison.json').write_text(json.dumps(results,indent=2))
print('COMPLETE',str(RUN),flush=True)
