#!/usr/bin/env python3
"""Isolated real-app fixture runner. Never reads T3 live state.
Use: python3 fixture-server.py start <before|after> <two-host|signed-out|signed-in> <modern|old>
     python3 fixture-server.py stop <run-directory>
Every start gets a fresh timestamped home, argv log, and server log.
"""
import datetime,json,os,pathlib,signal,subprocess,sys
ROOT=pathlib.Path('/tmp/lead-27840-r1/capture2')
FIXTURES=pathlib.Path((ROOT/'fixture-root.txt').read_text())
if sys.argv[1]=='stop':
    run=pathlib.Path(sys.argv[2]); pid=int((run/'pid').read_text())
    try: os.killpg(pid,signal.SIGTERM)
    except ProcessLookupError: pass
    print('stopped',pid);sys.exit()
side,fixture,version=sys.argv[2:]
run=ROOT/(datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%f')+'-'+side+'-'+fixture+'-'+version)
run.mkdir();(run/'bin').mkdir()
binary='/usr/bin/glab' if version=='modern' else '/tmp/lead-27840-r1/capture/glab-old/bin/glab'
wrapper=run/'bin/glab'
wrapper.write_text('#!/bin/sh\nprintf \'%s\\n\' "$*" >> '+str(run/'argv.log')+'\nexec '+binary+' "$@"\n')
wrapper.chmod(0o755)
env=dict(os.environ,T3CODE_DEV_SEED='0',T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD='0',GLAB_CONFIG_DIR=str(FIXTURES/fixture/'glab'))
env['PATH']=str(run/'bin')+':'+env['PATH']
cwd='/home/ubuntu/wt/pr-27840'+('-base' if side=='before' else '')
with (run/'server.log').open('w') as out:
    p=subprocess.Popen(['vp','run','dev','--home-dir',str(run/'home')],cwd=cwd,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True)
(run/'pid').write_text(str(p.pid));(run/'fixture.json').write_text(json.dumps(dict(side=side,fixture=fixture,version=version,cwd=cwd,binary=binary,pid=p.pid),indent=2))
print(run)
