#!/usr/bin/env python3
"""Real T3 server proof. Usage: python3 driver.py BASE_CHECKOUT HEAD_CHECKOUT.
Requires node, git, sqlite3. All runtime homes are fresh; no database row insertion.
Measures live SQLite execution (iterate to exhaustion), not whole HTTP request.
"""
import os,sys,json,time,subprocess,socket,urllib.request,statistics,sqlite3,datetime,pathlib
scratch=pathlib.Path(__file__).resolve().parent
out=scratch/('run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));out.mkdir()

def run_side(side,checkout):
    checkout=pathlib.Path(checkout).resolve();home=out/side; (home/'userdata').mkdir(parents=True)
    workspace=home/'workspace';workspace.mkdir();(workspace/'README.md').write_text('Synthetic performance proof\n')
    def git(*args):return subprocess.check_output(['git',*args],cwd=workspace,text=True).strip()
    git('init','-q','--initial-branch=main');git('add','.');git('-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-qm','Synthetic workspace')
    settings={'providerInstances':{x:{'driver':x,'enabled':False} for x in ['codex','claudeAgent','cursor','grok','muse','pi','opencode','antigravity']}}
    settings['providerInstances']['bulk']={'driver':'acpRegistry','enabled':True,'label':'Bulk commands','config':{'source':'local','commandPath':subprocess.check_output(['which','node'],text=True).strip(),'commandArgs':[str(scratch/'bulk-agent.mjs')],'customModels':['bulk']}}
    settings['defaultModelSelection']={'instanceId':'bulk','model':'bulk'}
    (home/'userdata/settings.json').write_text(json.dumps(settings))
    sock=socket.socket();sock.bind(('127.0.0.1',0));port=sock.getsockname()[1];sock.close()
    env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD':'0','PROOF_SQL_LOG':str(home/'sql.ndjson')}
    log=(home/'server.log').open('w');server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(home)],cwd=checkout,env=env,stdout=log,stderr=log)
    def cli(*args):
        p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,text=True,capture_output=True,timeout=900)
        if p.returncode:raise RuntimeError(f'CLI {args[:2]} exit {p.returncode}: {p.stdout} {p.stderr}')
        return p.stdout.strip()
    try:
        for _ in range(300):
            if (home/'userdata/server-runtime.json').exists():break
            if server.poll() is not None:raise RuntimeError('server exited: '+(home/'server.log').read_text()[-4000:])
            time.sleep(.1)
        token=cli('auth','session','issue','--token-only','--label','proof')
        cli('project','add',str(workspace),'--title','Synthetic shell query proof')
        origin=f'http://127.0.0.1:{port}'
        def shell():
            req=urllib.request.Request(origin+'/api/orchestration/shell',headers={'Authorization':'Bearer '+token,'x-t3-orchestration-protocol':'2'})
            t=time.perf_counter_ns()
            with urllib.request.urlopen(req,timeout=60) as r:body=json.load(r)
            return body,(time.perf_counter_ns()-t)/1e6
        def db():return sqlite3.connect('file:'+str(home/'userdata/statev2.sqlite')+'?mode=ro',uri=True)
        def count(status):
            with db() as conn:return conn.execute("select count(*) from orchestration_v2_projection_turn_items where type='command_execution' and json_extract(payload_json,'$.input')=? and status=?",('pending synthetic command' if status=='running' else 'echo synthetic',status)).fetchone()[0]
        def await_count(status,n):
            for _ in range(1800):
                if count(status)==n:return
                time.sleep(.1)
            raise RuntimeError(f'{status} expected {n}, got {count(status)}')
        started=json.loads(cli('thread','start',str(workspace),'BULK1000','--title','Synthetic bulk history','--provider','bulk','--model','bulk','--wait','--json'))
        tid=started['threadId'];await_count('completed',1000)
        cli('thread','send',tid,'BULKHANG','--json');await_count('running',1)
        results=[]
        def measure(n):
            for _ in range(5):shell()
            groups=[];last=None
            for batch in range(5):
                samples=[];http=[];vmSteps=[]
                for sample in range(21):
                    path=home/'sql.ndjson';offset=path.stat().st_size if path.exists() else 0
                    body,elapsed=shell();http.append(elapsed)
                    lines=path.read_text()[offset:].splitlines()
                    entries=[json.loads(x) for x in lines]
                    if len(entries)!=1:raise RuntimeError(f'Expected one pending query per shell GET; got {len(entries)}')
                    entry=entries[0];last=entry
                    if len(entry['rows'])!=1:raise RuntimeError('pending row count differs')
                    row=entry['rows'][0];payload=json.loads(row.get('payload_json',row[1] if isinstance(row,list) else '{}'))
                    if payload.get('status')!='running' or payload.get('type')!='command_execution':raise RuntimeError('wrong pending row: '+str(payload))
                    samples.append(entry['ms']);vmSteps.append(entry['vmStep'])
                groups.append({'statementMs':samples,'vmSteps':vmSteps,'medianMs':statistics.median(samples),'httpMs':http,'httpMedianMs':statistics.median(http)})
            plan=json.loads(subprocess.check_output(['node',str(scratch/'explain.mjs'),str(home/'userdata/statev2.sqlite'),json.dumps({'sql':last['sql'],'binds':last['binds']})],text=True))
            result={'completed':n,'running':count('running'),'groups':groups,'plan':plan,'statement':last['sql'],'binds':last['binds'],'returnedRows':last['rows'],'shellResponse':body}
            (home/f'measure-{n}.json').write_text(json.dumps(result,indent=2));results.append(result)
            print(side,n,'live SQL group medians ms:',[round(x['medianMs'],6) for x in groups],flush=True)
        measure(1000)
        stopped=subprocess.run(['node',str(scratch/'stop.mjs'),origin,tid],input=token,text=True,capture_output=True,timeout=60)
        if stopped.returncode:raise RuntimeError('Stop RPC failed: '+stopped.stdout+stopped.stderr)
        (home/'stop.txt').write_text(stopped.stdout)
        cli('thread','send',tid,'BULK14000','--wait','--json');await_count('completed',15000)
        cli('thread','send',tid,'BULKHANG','--json');await_count('running',1)
        measure(15000)
        sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
        return {'side':side,'sha':sha,'results':results}
    finally:
        server.terminate()
        try:server.wait(timeout=30)
        except subprocess.TimeoutExpired:server.kill();server.wait()
        log.close()

all_results=[]
for side,checkout in zip(['before','after'],sys.argv[1:]):
    print('Starting',side,flush=True)
    all_results.append(run_side(side,checkout))
(out/'results.json').write_text(json.dumps(all_results,indent=2))
print('Output:',out,flush=True)
