#!/usr/bin/env python3
"""Real VS Code reproduction; run inside headless-desktop.
Usage: python3 compare.py SCRATCH BASE_CHECKOUT HEAD_CHECKOUT
Requires official VS Code extracted to SCRATCH/VSCode-linux-x64 and Remote-SSH
installed in SCRATCH/extensions. URLs come directly from each checkout's code.
"""
import sys, json, time, subprocess, pathlib, signal, hashlib, os
root,base,head=map(pathlib.Path,sys.argv[1:])
run=root/time.strftime('capture-%Y%m%d-%H%M%S');run.mkdir()
code=root/'VSCode-linux-x64/bin/code'
wm=subprocess.Popen(['openbox'],stdout=open(run/'wm.log','w'),stderr=subprocess.STDOUT)
children=[]
def shell(args,**kw):return subprocess.run(list(map(str,args)),check=True,**kw)
def windows():
 s=subprocess.run(['wmctrl','-l'],capture_output=True).stdout.decode()
 return [dict(id=l.split()[0],title=' '.join(l.split()[3:])) for l in s.splitlines() if ' - Visual Studio Code' in l]
def wait_window(predicate,timeout=60):
 end=time.monotonic()+timeout
 while time.monotonic()<end:
  w=windows()
  if predicate(w):return w
  time.sleep(.25)
 raise RuntimeError('Window condition timed out: '+str(windows()))
def snap(name):
 # Stable stills: require identical screenshots 500ms apart.
 for i in range(60):
  a=subprocess.check_output(['import','-window','root','png:-'])
  time.sleep(.5)
  b=subprocess.check_output(['import','-window','root','png:-'])
  if a==b:
   (run/name).write_bytes(b);return
 raise RuntimeError('Screen did not stabilize')
results={}
try:
 for side,checkout in [('before',base),('after',head)]:
  profile=run/(side+'-profile');(profile/'User').mkdir(parents=True)
  settings={'workbench.startupEditor':'none','security.workspace.trust.enabled':False,
   'security.promptForRemoteFileProtocolHandling':False,'chat.disableAIFeatures':True,
   'workbench.enableExperiments':False,'telemetry.telemetryLevel':'off','update.mode':'none',
   'extensions.autoUpdate':False,'extensions.autoCheckUpdates':False,
   'remote.SSH.connectTimeout':5,'remote.SSH.configFile':str(root/'ssh-config'),
   'remote.SSH.showLoginTerminal':False,'window.title':'${rootName}${separator}${appName}',
   'editor.cursorBlinking':'solid','workbench.colorTheme':'Default Dark Modern'}
  (profile/'User/settings.json').write_text(json.dumps(settings))
  (root/'ssh-config').write_text('Host localhost\n  HostName localhost\n  User nobody\n  BatchMode yes\n  StrictHostKeyChecking no\n  UserKnownHostsFile /dev/null\n  ConnectTimeout 5\n')
  for project in ['projA','projB']:
   p=root/'projects'/project;p.mkdir(parents=True,exist_ok=True)
   (p/'README.md').write_text('# '+project+'\n\nSynthetic window-preservation demonstration.\n')
  args=[code,'--no-sandbox','--disable-gpu','--user-data-dir',profile,'--extensions-dir',root/'extensions']
  log=open(run/(side+'-code.log'),'w')
  proc=subprocess.Popen(list(map(str,args+[root/'projects/projA'])),stdout=log,stderr=subprocess.STDOUT);children.append(proc)
  initial=wait_window(lambda w:len(w)==1 and 'projA' in w[0]['title'])
  aid=initial[0]['id'];shell(['wmctrl','-ir',aid,'-b','remove,maximized_vert,maximized_horz'])
  shell(['wmctrl','-ir',aid,'-e','0,20,80,1860,900'])
  time.sleep(3)
  snap(side+'-initial.png')
  url=subprocess.check_output(['node','--input-type=module','-e',
   "import {buildRemoteOpenUrl} from './packages/contracts/src/editor.ts'; console.log(buildRemoteOpenUrl({editor:'vscode',host:'localhost',absolutePath:"+json.dumps(str(root/'projects/projB'))+"}))"],cwd=checkout).decode().strip()
  recorder=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-framerate','15','-video_size','1920x1080','-i',os.environ['DISPLAY'],
   '-vf',f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='{side.upper()} - {'a369642c1c' if side=='before' else '4b3bf590cb'} - Open remote projB from an existing projA window':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.9:x=20:y=15",'-c:v','libx264','-preset','ultrafast','-crf','22','-pix_fmt','yuv420p',str(run/(side+'.mp4'))])
  time.sleep(2)
  shell(args+['--open-url',url],stdout=log,stderr=subprocess.STDOUT)
  final=wait_window(lambda w:any('projB' in x['title'] for x in w))
  time.sleep(12)
  final=windows()
  # Tile only for the final observation; do not change the handoff itself.
  for i,w in enumerate(final):
   shell(['wmctrl','-ir',w['id'],'-b','remove,maximized_vert,maximized_horz'])
   shell(['wmctrl','-ir',w['id'],'-e',f'0,{20+i*950},80,{1860 if len(final)==1 else 930},900'])
  # Keep the native SSH failure dialog in-frame, away from either project title.
  all_windows=subprocess.check_output(['wmctrl','-l']).decode().splitlines()
  for line in all_windows:
   if line.endswith(' Visual Studio Code') and ' - Visual Studio Code' not in line:
    shell(['wmctrl','-ir',line.split()[0],'-e','0,610,770,700,130'])
  time.sleep(3)
  snap(side+'-final.png')
  time.sleep(3)
  recorder.send_signal(signal.SIGINT);recorder.wait(timeout=20)
  results[side]={'initial':initial,'final':final,'sameWindowReplaced':any(w['id']==aid and 'projB' in w['title'] for w in final),'projectAPreserved':any(w['id']==aid and 'projA' in w['title'] for w in final),'url':url}
  (run/'observations.json').write_text(json.dumps(results,indent=2))
  for w in final:shell(['wmctrl','-ic',w['id']])
  wait_window(lambda w:not w)
  proc.wait(timeout=20)
 print(run,flush=True)
 print(json.dumps(results,indent=2),flush=True)
finally:
 for p in children:
  if p.poll() is None:p.terminate()
 wm.terminate();wm.wait()
