import os, pathlib, subprocess, json, re, datetime, sys
root=pathlib.Path(__file__).resolve().parent
run=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run.mkdir()
results={}
for side,suffix,sha in [('before','-base','6ec46a61e60e1bbc60ef48b919d41b124632db7c'),('after','','a139d3203ecbe33e14c494da053c51520e3b0fb7')]:
    checkout=pathlib.Path(sys.argv[1 if side=='before' else 2]).resolve()
    home=run/side/'home'; home.mkdir(parents=True)
    (home/'policy.json').write_text('{"schemaVersion":1,"organization":"Tilde Corp"}\n')
    env={**os.environ,'HOME':str(home),'NO_COLOR':'1','T3CODE_DEV_SEED':'0'}
    lines=[f'{side.upper()} | {sha}', 'Linux x86_64 | built CLI | isolated synthetic HOME', '', '$ cat ~/policy.json', (home/'policy.json').read_text().strip()]
    checks=[]
    for label,option,out in [('literal tilde','--policy=~/policy.json','policy-templates-out'),('shell-expanded control',str(home/'policy.json'),'policy-templates-out2')]:
        args=[os.popen('which node').read().strip(),str(checkout/'apps/server/dist/bin.mjs'),'policy','templates',str(home/out)]
        args += [option] if label=='literal tilde' else ['--policy',option]
        lines += ['',f'$ t3 policy templates "$HOME/{out}" '+("'--policy=~/policy.json'" if label=='literal tilde' else '--policy ~/policy.json')]
        p=subprocess.run(args,env=env,cwd=checkout,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        output=re.sub(r'\x1b\[[0-9;]*m','',p.stdout).replace(str(home),'$HOME').replace(str(checkout),'[checkout]')
        lines += [output.strip(),f'Exit code: {p.returncode}']
        files=sorted(str(f.relative_to(home/out)) for f in (home/out).rglob('*') if f.is_file())
        lines += ['Generated files:'] + (['  '+f for f in files] or ['  (none)'])
        profile=home/out/'macos/t3code.mobileconfig'
        count=profile.read_text().count('Tilde Corp') if profile.exists() else 0
        lines += [f'MacOS profile occurrences of "Tilde Corp": {count}']
        checks.append({'label':label,'exit':p.returncode,'files':files,'organizationOccurrences':count})
    lines += ['', '$ printf "%s\\n" --policy=~/policy.json',subprocess.check_output(['bash','-c','printf "%s\\n" --policy=~/policy.json'],env=env,text=True).strip()]
    (run/(side+'.txt')).write_text('\n'.join(lines)+'\n')
    results[side]=checks
(run/'results.json').write_text(json.dumps(results,indent=2))
print(run)
print(json.dumps(results,indent=2))
