import os,sys,pathlib,subprocess,time,json,shlex,signal,hashlib
from PIL import Image,ImageDraw,ImageFont
ROOT=pathlib.Path(__file__).parent
side=sys.argv[1]; checkout=pathlib.Path(sys.argv[2]); run=ROOT/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));run.mkdir()
home=run/'home';home.mkdir();config=home/'cli-config';config.mkdir()
# The real installed Azure DevOps extension is copied, never replaced by a fake CLI.
import shutil
shutil.copytree(pathlib.Path.home()/'.azure/cliextensions',config/'azure/cliextensions')
values={}
for line in (pathlib.Path.home()/'.config/azure-devops-test.env').read_text().splitlines():
 if '=' in line and not line.startswith('#'):
  k,v=line.removeprefix('export ').split('=',1);values[k]=shlex.split(v)[0]
keys=['AZURE_CONFIG_DIR','AZURE_DEVOPS_CACHE_DIR','GH_CONFIG_DIR','GLAB_CONFIG_DIR']
profile=''.join('export '+k+'='+shlex.quote(str(config/v))+'\n' for k,v in zip(keys,['azure','azure-devops','gh','glab']))+'export PATH="$PATH:$HOME/profile-bin"\n'
(home/'.bash_profile').write_text(profile)
env={'HOME':str(home),'SHELL':'/bin/bash','PATH':'/usr/bin:/bin','T3CODE_HOME':str(run/'t3'),'T3CODE_DEV_SEED':'0','DISPLAY':os.environ['DISPLAY'],'DBUS_SESSION_BUS_ADDRESS':os.environ['DBUS_SESSION_BUS_ADDRESS']}
if 'XAUTHORITY' in os.environ:env['XAUTHORITY']=os.environ['XAUTHORITY']
def az(e,args):
 p=subprocess.run(['/usr/bin/az']+args,env={**e,'AZURE_DEVOPS_EXT_PAT':values['AZURE_DEVOPS_EXT_PAT']},stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,timeout=180);return p.returncode,p.stdout
shellenv=dict(x.split('=',1) for x in subprocess.check_output(['/bin/bash','-lc','env -0'],env=env).decode().split('\0') if '=' in x)
rc,out=az(shellenv,['devops','configure','--defaults','organization='+values['AZURE_DEVOPS_TEST_ORG']]); assert rc==0,out
rc,out=az(shellenv,['devops','project','list','--query','length(value)','-o','tsv','--only-show-errors']);assert rc==0,out
control=out.strip()
log=open(run/'desktop.log','w')
electron=checkout/'apps/desktop/node_modules/electron/dist/electron'
p=subprocess.Popen([str(electron),'--no-sandbox','--disable-gpu',str(checkout/'apps/desktop/dist-electron/main.cjs')],cwd=checkout,env=env,stdout=log,stderr=log)
def descendants(pid):
 result=[]
 try: children=pathlib.Path(f'/proc/{pid}/task/{pid}/children').read_text().split()
 except FileNotFoundError:return result
 for c in children:result.append(int(c));result.extend(descendants(int(c)))
 return result
try:
 serverenv=None
 for _ in range(120):
  for pid in descendants(p.pid):
   try:
    e=dict(x.split('=',1) for x in pathlib.Path(f'/proc/{pid}/environ').read_bytes().decode().split('\0') if '=' in x)
    cmd=pathlib.Path(f'/proc/{pid}/cmdline').read_bytes()
    if e.get('ELECTRON_RUN_AS_NODE')=='1' and b'bin.mjs' in cmd:serverenv=e;serverpid=pid;break
   except (OSError,UnicodeError):pass
  if serverenv:break
  if p.poll() is not None:raise RuntimeError('Electron exited: '+str(p.returncode))
  time.sleep(1)
 assert serverenv,'backend not found'
 # Allow the real window and backend to finish starting.
 time.sleep(8)
 def safe(t):
  t=t.replace(str(home),'$HOME').replace(str(run),'$RUN').replace(str(checkout),'$CHECKOUT')
  for k,v in values.items():t=t.replace(v,'<test organization>' if 'ORG' in k else '<test project>' if 'PROJECT' in k else '<redacted>')
  return t
 lines=[side.upper()+' | Desktop login-shell configuration', 'Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'', 'Real Electron build, Linux / Xvfb, fresh HOME and T3CODE_HOME', 'Launch environment: PATH=/usr/bin:/bin; SHELL=/bin/bash', 'CLI config variables absent from launch; exported in .bash_profile', '', 'Login-shell control: az devops project list', 'exit=0; project count='+control,'', 'Observed real Electron backend environment (/proc child environ):','PATH includes profile-bin: '+str(str(home/'profile-bin') in serverenv.get('PATH',''))]
 for k in keys:lines.append(k+'='+safe(serverenv.get(k,'unset')))
 caches=list((run/'t3').rglob('shell-environment-cache.json'))
 if caches:
  cache=json.loads(caches[0].read_text());lines+=['','Persisted shell-environment-cache.json:',safe(json.dumps(cache,indent=2))]
 # Avoid extension download noise: copy the same real extension to fallback location.
 shutil.copytree(config/'azure/cliextensions',home/'.azure/cliextensions',dirs_exist_ok=True)
 rc,out=az(serverenv,['devops','project','list','--query','length(value)','-o','tsv','--only-show-errors'])
 lines+=['','Same az command with exact backend environment + same PAT:', '$ az devops project list --query "length(value)" -o tsv',safe(out.strip()),'exit='+str(rc)]
 lines+=['','Real azure-devops extension preinstalled in both config locations.', 'No fake CLI, service, or API responses used.']
 text='\n'.join(lines);(run/'evidence.txt').write_text(text+'\n')
 # Show sanitized real command output in a terminal and capture its stable window.
 term=subprocess.Popen(['gnome-terminal','--wait','--title=CLI evidence','--geometry=145x48+0+0','--hide-menubar','--','/bin/bash','-c','cat "$1"; read -r _', 'evidence',str(run/'evidence.txt')],stdout=log,stderr=log)
 try:
  wid=None
  for _ in range(30):
   q=subprocess.run(['xdotool','search','--name','^CLI evidence$'],capture_output=True,text=True)
   if q.returncode==0:wid=q.stdout.splitlines()[-1];break
   time.sleep(.5)
  assert wid,'terminal window not found'
  previous=None
  for _ in range(20):
   subprocess.run(['import','-window',wid,str(run/'commands.png')],check=True)
   current=hashlib.sha256((run/'commands.png').read_bytes()).hexdigest()
   if current==previous:break
   previous=current;time.sleep(.5)
  else:raise RuntimeError('terminal screenshot not stable')
  subprocess.run(['xdotool','windowfocus',wid,'key','Return'],check=True)
  term.wait(timeout=10)
 finally:
  if term.poll() is None:term.terminate()
 (ROOT/(side+'-run.json')).write_text(json.dumps({'run':str(run),'rc':rc,'profilePath':str(home),'projectCount':out.strip(),'configVars':{k:serverenv.get(k) for k in keys}},indent=2))
 print(str(run));print(safe(text))
finally:
 for pid in reversed(descendants(p.pid)):
  try:os.kill(pid,signal.SIGTERM)
  except ProcessLookupError:pass
 p.terminate()
 try:p.wait(timeout=10)
 except subprocess.TimeoutExpired:p.kill();p.wait()
