#!/usr/bin/env python3
"""Real CLI proof. Usage: prove.py ARCHIVE BASE_EXE HEAD_EXE OUTPUT_DIR.
Build both executables with `node apps/server/scripts/cli.ts build-exe`.
Build the unchanged release assets using scripts/build-cli-archive.ts.
All fixtures are synthetic; /sandbox in transcripts replaces the fixture root.
"""
import datetime,json,os,pathlib,shutil,subprocess,sys,tarfile,time
archive,base,head,out=sys.argv[1:]
out=pathlib.Path(out)/datetime.datetime.now().strftime('%Y%m%dT%H%M%S'); out.mkdir(parents=True)
for side,exe,sha in [('before',base,'5f506c42624f60e7109f5fc4d82e642bbcd0397a'),('after',head,'e5735a823171f81594921e9f9bf0a120df836e0c')]:
    events=[]; lines=[]; start=time.monotonic()
    def emit(s):
        lines.append(s);events.append([round(time.monotonic()-start,6),'o',s+'\r\n'])
    emit(f'{side.upper()} | commit {sha[:10]} | Linux x86_64 | POSIX shell')
    emit('Real built executable; full release assets; fresh synthetic home per case.')
    for mode in ['launcher-on-PATH','direct-with-PATH','recorded-only']:
        root=out/side/mode; version=root/'h/.t3/runtime/versions/1.0.0';version.mkdir(parents=True)
        with tarfile.open(archive) as tar:
            prefix=tar.getmembers()[0].name.split('/')[0]+'/'
            for m in tar.getmembers():
                if m.name.startswith(prefix) and m.name[len(prefix):]:
                    m.name=m.name[len(prefix):];tar.extract(m,version,filter='data')
        shutil.copy2(exe,version/'t3');(version/'t3').chmod(0o755)
        home=root/'h';t3home=home/'.t3'; bindir=root/'bin';bindir.mkdir()
        (home/'alias').symlink_to(t3home,target_is_directory=True)
        (t3home/'userdata').mkdir();(t3home/'userdata/marker').write_text('preserve userdata\n')
        launcher=bindir/'t3';launcher.write_text(f'#!/bin/sh\nexec \'{home}/alias/runtime/versions/1.0.0/t3\' "$@"\n');launcher.chmod(0o755)
        other=bindir/'mytool';other.write_text('#!/bin/sh\necho unrelated-wrapper\n');other.chmod(0o755)
        (t3home/'runtime/launchers').write_text(str(launcher)+'\n')
        cwd=root/'elsewhere';cwd.mkdir()
        env={**os.environ,'HOME':str(home),'XDG_CONFIG_HOME':str(home/'.config'),'XDG_DATA_HOME':str(home/'.local/share'),'NO_COLOR':'1','TERM':'dumb','PATH':str(bindir)+':/usr/bin:/bin' if mode!='recorded-only' else '/usr/bin:/bin'}
        def clean(s):return s.replace(str(root),'/sandbox')
        emit('');emit('CASE: '+mode)
        emit("Fixture: h/alias -> h/.t3; bin/t3 is the unedited generated script.")
        emit('Recorded: bin/t3; userdata/marker and unrelated bin/mytool exist.')
        external=root/'standalone/t3'
        if mode=='recorded-only':
            shutil.copytree(version,external.parent,copy_function=os.link)
            emit('Invocation: standalone copy outside this home; launcher absent from PATH.')
        cmd=['t3' if mode=='launcher-on-PATH' else str(external if mode=='recorded-only' else version/'t3'),'uninstall','--base-dir',str(t3home),'--yes']
        emit('$ '+clean(' '.join(cmd)))
        p=subprocess.Popen(cmd,cwd=cwd,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
        for line in p.stdout:emit(clean(line.rstrip()))
        emit('uninstall exit: '+str(p.wait()))
        emit('CHECK launcher exists: '+str(launcher.exists()).lower())
        emit('CHECK runtime exists: '+str((t3home/'runtime').exists()).lower())
        emit('CHECK userdata unchanged: '+str((t3home/'userdata/marker').read_text()=='preserve userdata\n').lower())
        p=subprocess.run([str(other)],capture_output=True,text=True);emit('CHECK unrelated wrapper: '+p.stdout.strip()+f' (exit {p.returncode})')
        if launcher.exists():
            p=subprocess.run([str(launcher),'--version'],env=env,capture_output=True,text=True)
            emit('$ /sandbox/bin/t3 --version');emit(clean(p.stderr.strip()));emit('launcher exit: '+str(p.returncode))
    (out/f'{side}.txt').write_text('\n'.join(lines)+'\n')
    with (out/f'{side}.cast').open('w') as f:
        f.write(json.dumps({'version':2,'width':130,'height':46,'title':f'{side} CLI uninstall proof'})+'\n')
        for event in events:f.write(json.dumps(event)+'\n')
    print('\n'.join(lines))
print('OUTPUT_DIR='+str(out))
