import os,sys,pathlib,subprocess,datetime,json,time,shlex,re
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('run-%Y%m%d-%H%M%S')
run.mkdir()
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    sha=subprocess.check_output(['git','-C',checkout,'rev-parse','HEAD'],text=True).strip()
    text=f'T3 Code real CLI | Linux | Node '+subprocess.check_output(['node','--version'],text=True).strip()+f'\nCommit: {sha}\nFresh isolated database for each registration order.\n<workspace> denotes the synthetic working directory.\n\n'
    events=[];start=time.monotonic()
    def emit(s):
        global text
        text+=s
        events.append([round(time.monotonic()-start,3),'o',s.replace('\n','\r\n')])
    events.append([0,'o',text.replace('\n','\r\n')])
    for order in [1,2]:
        cwd=run/side/f'order-{order}'
        cwd.mkdir(parents=True)
        (cwd/' notes').mkdir();(cwd/'notes').mkdir()
        state=cwd/'state'
        emit(f'=== Order {order}: '+('leading-space folder first' if order==1 else 'sibling first')+' ===\nFolders exist: " notes", "notes"\n')
        adds=[['add',' notes','--title','Literal'],['add','notes','--title','Sibling']]
        if order==2:adds.reverse()
        commands=adds+[['rename',' notes','Renamed'],['remove',' notes'],['rename','notes','Sibling']]
        for args in commands:
            emit('$ t3 project '+shlex.join(args)+ ' --base-dir <isolated-state>\n')
            proc=subprocess.run(['node',checkout+'/apps/server/src/bin.ts','project',*args,'--base-dir',str(state)],cwd=cwd,env={**os.environ,'T3CODE_DEV_SEED':'0','NO_COLOR':'1'},stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
            out=proc.stdout.replace(str(cwd),'<workspace>').replace(checkout,'<checkout>')
            out=re.sub(r'\x1b\[[0-9;]*m','',out)
            emit(out+f'[exit {proc.returncode}]\n\n')
    (run/f'{side}.txt').write_text(text)
    with (run/f'{side}.cast').open('w') as f:
        f.write(json.dumps({'version':2,'width':160,'height':50,'title':f'T3 CLI {side} {sha[:10]}','env':{'TERM':'xterm-256color'}})+'\n')
        for e in events:f.write(json.dumps(e)+'\n')
    print(text,flush=True)
print('ARTIFACTS',run)
