import os,sys,subprocess,json,time,pathlib,re
root=pathlib.Path(os.environ['MAC_WORK'])
side=sys.argv[1]
run=root/('run-'+side+'-'+str(int(time.time())))
run.mkdir()
home=run/'data'
env=dict(os.environ,T3CODE_HOME=str(home),T3CODE_DEV_SEED='0',NO_COLOR='1',FORCE_COLOR='0')
cli=['node',str(root/side/'apps/server/dist/bin.mjs'),'service']
target='gui/'+str(os.getuid())+'/com.t3tools.t3code.service'
events=[]
def call(title,args):
    start=time.monotonic()
    p=subprocess.run(args,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
    out=p.stdout.replace(str(root),'<workspace>').replace(str(pathlib.Path.home()),'<home>')
    if args[:2]==['launchctl','print-disabled']:
        out='\n'.join(x for x in out.splitlines() if 'com.t3tools.t3code.service' in x)+'\n'
    elif args[:2]==['launchctl','print'] and p.returncode==0:
        out='\n'.join(x for x in out.splitlines() if any(k in x for k in ['state =', 'program =', 'pid =', 'last exit code =']))+'\n'
    out=re.sub(r'\x1b\[[0-9;]*[A-Za-z]','',out)
    events.append(dict(step=title,command=' '.join(args).replace(str(root),'<workspace>'),exit=p.returncode,output=out,seconds=round(time.monotonic()-start,2)))
    print('\n### '+title+'\n'+out+'Exit: '+str(p.returncode),flush=True)
    (run/'events.json').write_text(json.dumps(events,indent=2))
    return p
print('macOS 26.6.2 / Apple silicon / real Node CLI / fresh isolated T3 home',flush=True)
call('1. Install',['node',str(root/side/'apps/server/dist/bin.mjs'),'service','install','--base-dir',str(home)])
call('2. Confirm loaded',['launchctl','print',target])
call('3. Healthy status',cli+['status','--base-dir',str(home)])
call('4. Unload and wait',['launchctl','bootout','--wait',target])
call('5. Confirm unloaded',['launchctl','print',target])
call('6. Unloaded status',cli+['status','--base-dir',str(home)])
call('7. Disable',['launchctl','disable',target])
call('8. Confirm disabled',['launchctl','print-disabled','gui/'+str(os.getuid())])
call('9. Disabled status',cli+['status','--base-dir',str(home)])
call('10. Repair',cli+['install','--base-dir',str(home)])
call('11. Status after repair',cli+['status','--base-dir',str(home)])
call('12. Loaded after repair',['launchctl','print',target])
call('13. Overrides after repair',['launchctl','print-disabled','gui/'+str(os.getuid())])
call('14. Uninstall',cli+['uninstall','--base-dir',str(home)])
call('15. Restore enabled override',['launchctl','enable',target])
print('RUN_DIR='+str(run),flush=True)
