import subprocess as sp, pathlib, time, json, sys, os, threading
checkout=pathlib.Path(sys.argv[1]).resolve(); out=pathlib.Path(sys.argv[2]).resolve(); side=sys.argv[3]
out.mkdir(parents=True,exist_ok=True); volume=out/'volume'; volume.mkdir()
name='pid-reuse-proof-'+out.name; replacement=name+'-replacement'; events=[]; started=time.monotonic()
def emit(s):
    print(s,flush=True); events.append([round(time.monotonic()-started,3),s]); (out/'events.json').write_text(json.dumps(events))
def run(args,**kw): return sp.run(args,text=True,stdout=sp.PIPE,stderr=sp.STDOUT,**kw)
def clean(s):
    return s.replace(str(checkout),'/workspace').replace(str(volume),'/volume')
common=['--user',str(os.getuid())+':'+str(os.getgid()),'-v',str(checkout.parent.parent)+':'+str(checkout.parent.parent)+':ro','-v',str(volume)+':/volume','-w',str(checkout),'-e','HOME=/tmp','-e','T3CODE_DEV_SEED=0','-e','NO_COLOR=1']
cli=['node','apps/server/dist/bin.mjs','start','--base-dir','/volume','--no-browser','--host','127.0.0.1','--port','3773']
state=volume/'userdata/server-runtime.json'
def wait_ready(proc=None):
    for _ in range(180):
        if state.exists():
            r=run(['docker','exec',replacement if proc else name,'node','-e',"fetch('http://127.0.0.1:3773/.well-known/t3/environment',{signal:AbortSignal.timeout(3000)}).then(r=>{console.log(r.status);process.exit(0)}).catch(()=>process.exit(1))"])
            if r.returncode==0 and r.stdout.strip()=='200':
                published=json.loads(state.read_text())
                if not proc or (published['pid']!=original['pid'] and published.get('ownerId')!=original.get('ownerId')):
                    return published,r.stdout.strip()
        if proc and proc.poll() is not None:return None,None
        if not proc and run(['docker','inspect','-f','{{.State.Running}}',name]).stdout.strip()!='true':raise RuntimeError('original container stopped')
        time.sleep(.5)
    raise RuntimeError('startup did not become ready')
try:
    emit('Linux Docker / Node 24 / fresh persistent volume')
    emit('Commit: '+run(['git','-C',str(checkout),'rev-parse','HEAD']).stdout.strip())
    emit('$ t3 start --base-dir /volume --no-browser --host 127.0.0.1 --port 3773')
    r=run(['docker','run','-d','--name',name,*common,'--entrypoint','node','node:24-bookworm',*cli[1:]])
    if r.returncode:raise RuntimeError(r.stdout)
    original,status=wait_ready(); emit('Original server ready: PID '+str(original['pid'])+', HTTP '+status)
    emit('Runtime has ownerId: '+str(bool(original.get('ownerId')))+'; server-owner.sqlite exists: '+str((volume/'userdata/server-owner.sqlite').exists()))
    emit('CONTROL: start a second server while original owner is live')
    r=run(['docker','exec',name,*cli]); (out/'control-raw.txt').write_text(r.stdout)
    control_exit=r.returncode; emit('Second start exit: '+str(r.returncode))
    emit('Already-running error: '+str('A T3 Code server is already running' in r.stdout))
    emit('Original runtime unchanged: '+str(json.loads(state.read_text())==original))
    emit('$ docker kill <original-container>  # abrupt SIGKILL; retain volume')
    run(['docker','kill',name]);run(['docker','rm',name])
    emit('Stale runtime retained unchanged: '+str(json.loads(state.read_text())==original))
    r=run(['docker','run','-d','--name',replacement,*common,'--entrypoint','sleep','node:24-bookworm','3600'])
    if r.returncode:raise RuntimeError(r.stdout)
    r=run(['docker','exec',replacement,'sh','-c','printf "PID 1 command: "; cat /proc/1/comm'])
    emit(r.stdout.strip());
    lock=run(['docker','exec',replacement,'node','--input-type=module','-e',"import {DatabaseSync} from 'node:sqlite'; const db=new DatabaseSync('/volume/userdata/server-owner.sqlite',{readOnly:true,timeout:0}); db.prepare('SELECT 1 FROM sqlite_schema').get(); db.close(); console.log('Retained ownership database is readable: lock released');"]); emit(lock.stdout.splitlines()[0]);
    emit('Recorded server PID is now live unrelated process: '+str(original['pid']==1))
    emit('REDEPLOY: run the same t3 start against the retained volume')
    log=open(out/'redeploy-raw.txt','w');proc=sp.Popen(['docker','exec',replacement,*cli],text=True,stdout=log,stderr=sp.STDOUT)
    new,status=wait_ready(proc)
    if new:
        emit('Replacement server ready: PID '+str(new['pid'])+', HTTP '+status)
        emit('New ownerId published: '+str(new.get('ownerId')!=original.get('ownerId')))
        emit('Runtime PID changed from 1: '+str(new['pid']!=1))
        emit('RESULT: startup succeeds despite unrelated process reusing old PID')
    else:
        log.flush();raw=(out/'redeploy-raw.txt').read_text()
        emit('Replacement start exit: '+str(proc.returncode));emit('Already-running error: '+str('A T3 Code server is already running' in raw))
        for line in raw.splitlines():
            if 'A T3 Code server is already running' in line:emit(clean(line.strip()))
        emit('Runtime still points to sleep PID 1: '+str(json.loads(state.read_text())==original))
        emit('RESULT: startup incorrectly refuses the stale record')
    (out/'verdict.json').write_text(json.dumps({'original':original,'new':new,'controlExit':control_exit,'ready':new is not None},indent=2))
finally:
    for n in [name,replacement]:run(['docker','rm','-f',n])
    emit('Cleanup: both proof containers removed')
    (out/'transcript.txt').write_text('\n'.join(s for _,s in events)+'\n')
