import os,sys,subprocess,json,pathlib,datetime,re,textwrap,time
from PIL import Image,ImageDraw,ImageFont
root=pathlib.Path(__file__).parent
out=root/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ');out.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    cwd=out/side;cwd.mkdir();(cwd/'nyx.json').write_text(json.dumps({'name':'Nyx','appearance':'dark','canvas':'#1a1b26','accent':'#7aa2f7'}))
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    env={**os.environ,'NO_COLOR':'1','TERM':'dumb','T3CODE_DEV_SEED':'0'}
    transcript=f'{side.upper()} | Linux CLI | Node '+subprocess.check_output(['node','--version'],text=True).strip()+f'\nCommit: {sha}\nFresh isolated state; synthetic Nyx dark theme\n'
    for args in [['theme','set','--help'],['theme','--help'],['theme','set','nyx.json','--base-dir','state'],['theme','show','--base-dir','state']]:
        p=subprocess.run(['node',str(pathlib.Path(checkout)/'apps/server/src/bin.ts'),*args],cwd=cwd,env=env,text=True,capture_output=True,timeout=120)
        transcript+='\n$ t3 '+' '.join(args)+'\n'+p.stdout+p.stderr+f'[exit {p.returncode}]\n'
        if p.returncode: raise RuntimeError(transcript)
    code='import {ThemeToolkit} from "./src/mcp/toolkits/theme/tools.ts"; console.log(ThemeToolkit.tools.t3_theme_set.description)'
    p=subprocess.run(['node','--input-type=module','-e',code],cwd=pathlib.Path(checkout)/'apps/server',env=env,text=True,capture_output=True,timeout=120)
    if p.returncode: raise RuntimeError(p.stderr)
    transcript+='\n$ Runtime-loaded t3_theme_set description\n'+p.stdout
    transcript=re.sub(r'\x1b\[[0-9;]*m','',transcript).replace(str(cwd),'<isolated-directory>')
    (out/f'{side}.txt').write_text(transcript)
    # Render the complete captured command transcript; wrap only for legibility.
    lines=[w for line in transcript.splitlines() for w in (textwrap.wrap(line,105,replace_whitespace=False,drop_whitespace=False) or [''])]
    def capture():
        im=Image.new('RGB',(1220,len(lines)*25+48),'#10151d');d=ImageDraw.Draw(im)
        for n,line in enumerate(lines):d.text((24,24+n*25),line,font=font,fill='#e6edf3')
        return im
    a=capture();time.sleep(.5);b=capture();assert a.tobytes()==b.tobytes();b.save(out/f'{side}.png')
print(out)
