import os, sys, subprocess, pathlib, datetime
root=pathlib.Path(__file__).parent
run=root/datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
run.mkdir()
for side, checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    folder=run/side; home=folder/'home'; cwd=folder/'cwd'
    home.mkdir(parents=True); cwd.mkdir()
    env={**os.environ,'HOME':str(home),'NO_COLOR':'1','T3CODE_DEV_SEED':'0'}
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    lines=[side.upper()+' — '+sha,'Linux x86_64 | Node '+subprocess.check_output(['node','--version'],text=True).strip(), 'Fresh isolated HOME and separate empty CWD. Paths shown as $HOME / $CWD.', '']
    def cli(args):
        p=subprocess.run(['node',str(pathlib.Path(checkout)/'apps/server/src/bin.ts'),'policy','templates',*args],cwd=cwd,env=env,text=True,capture_output=True)
        lines.extend([p.stdout.strip(),p.stderr.strip(),f'Exit: {p.returncode}'])
    lines.append("$ t3 policy templates '~/t3-policy-templates'")
    cli(['~/t3-policy-templates'])
    lines.append('\n$ find "$CWD" -type f')
    lines.extend('$CWD/'+str(p.relative_to(cwd)) for p in sorted(cwd.rglob('*')) if p.is_file())
    lines.append('\n$ find "$HOME/t3-policy-templates" -type f')
    target=home/'t3-policy-templates'
    if not target.exists(): lines.append('No such file or directory')
    else: lines.extend('$HOME/'+str(p.relative_to(home)) for p in sorted(target.rglob('*')) if p.is_file())
    (home/'p.json').write_text('{"schemaVersion":1,"organization":"Tilde Corp"}')
    lines.append("\n$ t3 policy templates ctrl-out --policy='~/p.json'")
    cli(['ctrl-out','--policy=~/p.json'])
    profile=cwd/'ctrl-out/macos/t3code.mobileconfig'
    lines.append('Control profile contains Tilde Corp: '+str(profile.exists() and 'Tilde Corp' in profile.read_text()))
    text='\n'.join(l for l in lines if l!='')+'\n'
    text=text.replace(str(home),'$HOME').replace(str(cwd),'$CWD')
    (root/(side+'.txt')).write_text(text)
    print(text)
