import os,sys,json,time,subprocess,pathlib,threading,re,socket,urllib.request
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
side,checkout=sys.argv[1:3]
run=root/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));run.mkdir()
home=run/'home';backup=home/'runtime/db-backup/update-repro-1';backup.mkdir(parents=True)
print('Seeding 2,000,000 empty backup files',flush=True)
for d in range(2000):
 p=backup/str(d);p.mkdir()
 for f in range(1000): (p/str(f)).touch()
 if d%500==0: print('Seeded',d*1000,flush=True)
(home/'userdata').mkdir()
state=home/'runtime/service-state.json'
state.write_text(json.dumps({'protocol':4,'activeVersion':'0.1.10','update':{'id':'update-repro-1','fromVersion':'0.1.10','targetVersion':'0.1.11','dbPath':str(home/'userdata/statev2.sqlite'),'status':'pending'}}))
for version in ['0.1.10','0.1.11']:
 p=home/'runtime/versions'/version;p.mkdir(parents=True)
 (p/'.install-complete').write_text(version)
 (p/'t3').write_text('#!/bin/sh\nexec '+sys.argv[3]+' '+checkout+'/apps/server/dist/bin.mjs "$@"\n');(p/'t3').chmod(0o755)
(home/'service.env').write_text('T3CODE_PORT=38173\nT3CODE_HOST=127.0.0.1\nT3CODE_NO_BROWSER=true\nT3CODE_LAN=false\n')
observer=root/'observer.mjs'
observer.write_text('''import fs from 'node:fs';
if(process.send && process.env.T3_SERVICE_LAUNCHER_CONTEXT){
 const c=JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
 const present=()=>fs.existsSync(process.env.EVIDENCE_BACKUP);
 console.log('[IPC observer] real server started; pid='+process.pid);
 const send=process.send.bind(process);
 process.send=(...args)=>{console.log('[IPC observer] SEND '+JSON.stringify(args[0]));return send(...args)};
 process.on('message',m=>console.log('[IPC observer] RECEIVE '+JSON.stringify(m)+'; backupPresent='+present()));
}
''')
env={**os.environ,'T3CODE_HOME':str(home),'T3CODE_DEV_SEED':'0','T3CODE_NO_BROWSER':'true','NODE_OPTIONS':'--import='+str(observer),'EVIDENCE_BACKUP':str(backup)}
# Do not inherit a user's dev auth configuration.
env.pop('T3CODE_DEV_AUTH_TOKEN',None)
start=time.monotonic(); events=[]; lock=threading.Lock()
def log(line):
 line=re.sub(r'\x1b\[[0-9;]*m','',line).replace(str(run),'$RUN').replace(checkout,'$CHECKOUT').replace(str(pathlib.Path.home()),'$HOME')
 line=re.sub(r'(https?://[^\s]*[?](?:[^\s]*))','[pairing URL omitted]',line)
 if any(x in line for x in ['Token:', 'Pairing URL:', 'App link:', '█','▀','▄']): return
 with lock:
  events.append((round(time.monotonic()-start,2),line))
  with (run/'transcript.txt').open('a') as f:f.write(f'{events[-1][0]:7.2f}s {line}\n')
 print(line,flush=True)
sha=subprocess.check_output(['git','-C',checkout,'rev-parse','HEAD'],text=True).strip()
log(f'{side.upper()} commit {sha} | Linux x86_64, ext4 | real built CLI')
log('Fresh home; pending 0.1.10 -> 0.1.11; existing backup: 2,000,000 files')
proc=None
def launch():
 global proc
 proc=subprocess.Popen([sys.argv[3],checkout+'/apps/server/dist/bin.mjs','__service-launcher'],cwd=checkout,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 log('COMMAND: t3 __service-launcher; launcher pid='+str(proc.pid))
 def read():
  for line in proc.stdout:log(line.rstrip())
 threading.Thread(target=read,daemon=True).start()
launch()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',15)
video=subprocess.Popen(['ffmpeg','-loglevel','error','-y','-f','rawvideo','-pixel_format','rgb24','-video_size','1600x1000','-framerate','2','-i','-','-c:v','libx264','-preset','fast','-crf','23','-pix_fmt','yuv420p',str(run/(side+'.mp4'))],stdin=subprocess.PIPE)
prev=None;lastBackup=True;restarted=False;exitSeen=False;committedAt=None;end=None
try:
 while time.monotonic()-start<300:
  elapsed=time.monotonic()-start
  st=json.loads(state.read_text()); status=st['update']['status']
  if status!=prev:log('STATE: activeVersion='+st['activeVersion']+'; update.status='+status);prev=status;committedAt=elapsed if status=='committed' else None
  exists=backup.exists()
  if exists!=lastBackup:log('BACKUP: cleanup finished (directory gone)');lastBackup=exists
  if proc.poll() is not None and not exitSeen:
   log('LAUNCHER EXIT: code='+str(proc.returncode));exitSeen=True
   if side=='before' and status=='committed' and not exists:
    log('Restarting launcher once, standing in for service-manager KeepAlive');launch();restarted=True;end=elapsed+40
  if not exists and side=='after' and end is None:end=elapsed+40
  if end and elapsed>=end:break
  image=Image.new('RGB',(1600,1000),'#101822');draw=ImageDraw.Draw(image)
  draw.text((28,22),f'{side.upper()} | real service launcher | {sha[:10]} | elapsed {elapsed:5.1f}s',font=font,fill='#f2f5fa')
  draw.text((28,58),f'activeVersion {st["activeVersion"]}  status {status}  backup present {exists}  launcher alive {proc.poll() is None}',font=font,fill='#83e7c0')
  with lock:current=list(events)
  # Keep decisive events visible while displaying recent output.
  decisive=[e for e in current if any(x in e[1] for x in ['[IPC observer]','STATE:','BACKUP:','LAUNCHER EXIT:','Restarting','did not respond','startup failed','disconnected'])]
  rows=decisive[-19:]
  rows+=[e for e in current[-7:] if e not in rows]
  y=108
  import textwrap
  for t,line in rows:
   for wrapped in textwrap.wrap(f'{t:7.2f}s {line}',width=165):
    draw.text((28,y),wrapped,font=small,fill='#ffb5aa' if ('Error' in line or 'failed' in line or 'EXIT' in line) else '#d8e1ed');y+=22
  video.stdin.write(image.tobytes())
  image.save(run/(side+'.png'))
  time.sleep(.5)
 log('END OBSERVATION: launcher alive='+str(proc.poll() is None)+'; manual restart='+str(restarted))
finally:
 if proc and proc.poll() is None:
  proc.terminate()
  try:proc.wait(timeout=20)
  except subprocess.TimeoutExpired:proc.kill();proc.wait()
 video.stdin.close();video.wait()
 (run/'events.json').write_text(json.dumps(events,indent=2))
 print('RUN_DIRECTORY='+str(run),flush=True)
