import os, pathlib, subprocess, datetime, re, json, sys
root=pathlib.Path(__file__).resolve().parent
run=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); run.mkdir()
for side, checkout in [('before',pathlib.Path(sys.argv[1]).resolve()),('after',pathlib.Path(sys.argv[2]).resolve())]:
    fixture=run/side; home=fixture/'home'; config=fixture/'config'; shims=fixture/'bin'
    home.mkdir(parents=True); (config/'systemd/user').mkdir(parents=True); shims.mkdir()
    for name in ['busctl','systemctl','loginctl']:
        p=shims/name; p.write_text('#!/bin/sh\nexit 1\n'); p.chmod(0o755)
    (config/'systemd/user/t3code.service').write_text('[Service]\nEnvironment=T3CODE_HOME='+str(home)+'\n')
    env=dict(os.environ, XDG_CONFIG_HOME=str(config), PATH=str(shims)+os.pathsep+os.environ['PATH'], NO_COLOR='1', FORCE_COLOR='0')
    for key in ['T3CODE_HOST','T3CODE_LAN','T3CODE_HOME']: env.pop(key,None)
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    transcript=['Linux CLI | synthetic installed systemd user unit', 'Commit: '+sha, 'Service manager probes: failing shims; no live service modified.', '']
    for label, contents in [('Control: empty service.env',''),('Reproduction: host override, no LAN entry','T3CODE_HOST=0.0.0.0\n')]:
        (home/'service.env').write_text(contents)
        transcript += [label, '$ node apps/server/src/bin.ts status --base-dir <synthetic-home>']
        for suffix in [[],['--json']]:
            p=subprocess.run(['node','apps/server/src/bin.ts','status','--base-dir',str(home)]+suffix,cwd=checkout,env=env,text=True,capture_output=True)
            output=re.sub(r'\x1b\[[0-9;]*m','',p.stdout+p.stderr).replace(str(home),'<synthetic-home>')
            if suffix: (run/(side+'.json')).write_text(output)
            else: transcript += [output.rstrip(), 'Exit: '+str(p.returncode),'']
    (run/(side+'.txt')).write_text('\n'.join(transcript))
print(run)
