#!/usr/bin/env python3
"""Run unchanged installers against a real release; synchronize only publication scheduling.
Usage: python3 prove.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_ROOT
Requires Python Pillow and ffmpeg. Fresh timestamped homes, no user data.
"""
import os, sys, time, subprocess, threading, pathlib, json
from PIL import Image, ImageDraw, ImageFont
base,head,out=map(pathlib.Path,sys.argv[1:])
run=out/time.strftime('%Y%m%d-%H%M%S'); run.mkdir(parents=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
results={}
for side,checkout in [('before',base),('after',head)]:
    root=run/side; root.mkdir(); home=root/'home'; bins=root/'bin'; wrap=root/'wrap'; sync=root/'sync'
    for p in [bins,wrap,sync]: p.mkdir()
    target=home/'runtime/versions/0.1.10'
    # Existing owned launcher avoids the independent empty-launcher hard-link race.
    (bins/'t3').write_text("#!/bin/sh\nexec '"+str(target/ 't3')+"' \"$@\"\n"); (bins/'t3').chmod(0o755)
    (wrap/'mv').write_text('''#!/usr/bin/env python3
import os,sys,pathlib,time,subprocess
args=sys.argv[1:]; sync=pathlib.Path(os.environ['PROOF_SYNC']); who=os.environ['PROOF_INSTALLER']
if len(args)==2 and pathlib.Path(args[0]).name.startswith('.staging-'):
 print('[scheduler] installer '+who+' reached publication after destination removal',flush=True)
 (sync/('ready'+who)).touch()
 while not all((sync/('ready'+x)).exists() for x in ['1','2']): time.sleep(.01)
 if who=='2':
  while not (sync/'published1').exists(): time.sleep(.01)
 print('[scheduler] installer '+who+' executing real /usr/bin/mv',flush=True)
 result=subprocess.run(['/usr/bin/mv',*args]).returncode
 if who=='1': (sync/'published1').touch()
 sys.exit(result)
os.execv('/usr/bin/mv',['mv',*args])
'''); (wrap/'mv').chmod(0o755)
    sha=subprocess.check_output(['git','-C',str(checkout),'rev-parse','HEAD'],text=True).strip()
    lines=[]; lock=threading.Lock(); start=time.monotonic()
    def log(s):
        s=s.replace(str(root),'$RUN').replace(str(pathlib.Path.home()),'$USER_HOME')
        if 'Another t3 at ' in s: s='  Installed launcher is available at $RUN/bin/t3.'
        with lock: lines.append(s)
        print(side+': '+s,flush=True)
    log('T3 CLI concurrent install — '+side.upper()); log('Linux x86_64 | released CLI 0.1.10 | isolated fresh T3 home')
    log('Installer commit '+sha); log('Same home + version; publication barrier forces the reported interleaving.')
    frames=root/'frames'; frames.mkdir(); stop=threading.Event()
    def shot():
        im=Image.new('RGB',(1440,1000),'#10151e'); d=ImageDraw.Draw(im)
        with lock: visible=lines[-35:]
        for i,l in enumerate(visible): d.text((26,26+i*26),l[:121],font=font,fill='#d5e4f5')
        return im
    def record():
        n=0
        while not stop.is_set():
            shot().save(frames/f'{n:06}.png'); n+=1; stop.wait(.5)
    recorder=threading.Thread(target=record); recorder.start()
    procs=[]; readers=[]
    def read(proc,who):
        for line in proc.stdout: log('['+who+'] '+line.rstrip())
    for who in ['1','2']:
        env=os.environ.copy(); env.update(T3CODE_HOME=str(home),T3CODE_VERSION='0.1.10',T3CODE_INSTALL_BIN_DIR=str(bins),PROOF_SYNC=str(sync),PROOF_INSTALLER=who,NO_COLOR='1',PATH=str(wrap)+':'+os.environ['PATH'])
        p=subprocess.Popen(['sh',str(checkout/'scripts/install.sh')],env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
        procs.append(p); t=threading.Thread(target=read,args=(p,who)); t.start(); readers.append(t)
    codes=[p.wait(timeout=240) for p in procs]
    for t in readers: t.join()
    log('Installer exit codes: '+str(codes)); log('Inspection with hidden files visible (relative to runtime/versions):')
    nested=list(target.glob('.staging-*'))
    for p in sorted(target.iterdir()):
        log('  0.1.10/'+p.name+('/' if p.is_dir() else ''))
        if p in nested:
            for q in sorted(p.iterdir()): log('    '+p.name+'/'+q.name+('/' if q.is_dir() else ''))
    version=subprocess.check_output([str(target/'t3'),'--version'],text=True).strip(); log('Published executable --version: '+version)
    for p in nested:
        v=subprocess.check_output([str(p/'t3'),'--version'],text=True).strip(); log('Nested executable --version: '+v)
        log('Nested .install-complete: '+(p/'.install-complete').read_text().strip())
    log('Nested staging runtime count: '+str(len(nested)))
    log('RESULT: '+('BUG — complete duplicate retained despite both installers succeeding' if nested else 'CLEAN — one complete runtime; no nested staging copy'))
    time.sleep(3); shot().save(root/'inspection.png'); time.sleep(.5); shot().save(root/'inspection-confirm.png')
    stop.set(); recorder.join()
    (root/'transcript.txt').write_text('\n'.join(lines)+'\n')
    subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-framerate','2','-i',str(frames/'%06d.png'),'-c:v','libx264','-pix_fmt','yuv420p','-y',str(root/'recording.mp4')],check=True)
    results[side]={'sha':sha,'exitCodes':codes,'nestedCount':len(nested),'version':version,'directory':str(root)}
(run/'result.json').write_text(json.dumps(results,indent=2)); print('RESULT_DIRECTORY',run)
