import os, sys, json, pathlib, subprocess, socket, time, urllib.request, signal, datetime
from PIL import Image, ImageDraw, ImageFont
root=pathlib.Path(sys.argv[1]).resolve()
out=pathlib.Path(sys.argv[2]).resolve()/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S')
out.mkdir(parents=True)
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
results={}
for side,suffix in [('before','-base'),('after','')]:
    checkout=pathlib.Path(str(root)+suffix)
    sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
    home=out/side
    prefix=home/'node'
    entry=prefix/'lib/node_modules/t3/dist/bin.mjs'
    entry.parent.mkdir(parents=True)
    (prefix/'bin').mkdir()
    # A synthetic npm layout launching the actual unmodified server entrypoint.
    entry.write_text('import { runCliCommand } from '+json.dumps((checkout/'apps/server/src/binMain.ts').as_uri())+'; await runCliCommand();\n')
    version=json.loads((checkout/'apps/server/package.json').read_text())['version']
    (entry.parent.parent/'package.json').write_text(json.dumps({'name':'t3','version':version,'bin':{'t3':'./dist/bin.mjs'}}))
    (prefix/'bin/t3').symlink_to(entry)
    alias=home/'alias'
    alias.symlink_to(prefix,target_is_directory=True)
    lines=['T3 Code real-server capability capture',f'Commit: {sha}','Environment: Linux x64; native filesystem', 'Synthetic npm layout; fresh isolated data per launch','GET /.well-known/t3/environment','']
    results[side]={}
    for route in ['canonical','alias']:
      for mode in ['web','desktop']:
        with socket.socket() as s:
          s.bind(('127.0.0.1',0)); port=s.getsockname()[1]
        target=entry if route=='canonical' else alias/'lib/node_modules/t3/dist/bin.mjs'
        cmd=['node',str(target),'--mode',mode,'--host','127.0.0.1','--port',str(port),'--no-browser','--base-dir',str(home/(route+'-'+mode))]
        with (home/(route+'-'+mode+'.raw.log')).open('w') as log:
          p=subprocess.Popen(cmd,cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=log,stderr=log)
          try:
            deadline=time.monotonic()+90
            while True:
              try:
                with urllib.request.urlopen(f'http://127.0.0.1:{port}/.well-known/t3/environment',timeout=2) as response: descriptor=json.load(response)
                break
              except Exception:
                if p.poll() is not None or time.monotonic()>deadline: raise RuntimeError('server did not become ready')
                time.sleep(.25)
            c=descriptor['capabilities']
            install=c.get('serverInstallation')
            if install and 'prefix' in install:
                install={**install,'prefix':'<canonical npm prefix>' if install['prefix']==str(prefix) else '<unexpected prefix>'}
            row={'serverInstallation':install,'serverSelfUpdate':c.get('serverSelfUpdate')}
            results[side][route+'-'+mode]=row
            lines.extend([f'{route} entry / {mode} mode', '  '+json.dumps(row), ''])
          finally:
            p.send_signal(signal.SIGINT)
            try: p.wait(timeout=15)
            except subprocess.TimeoutExpired: p.kill();p.wait()
    text='\n'.join(lines)
    (out/(side+'.txt')).write_text(text+'\n')
    img=Image.new('RGB',(1280,620),'#111827');d=ImageDraw.Draw(img)
    # Wrap long JSON lines without truncation.
    y=25
    import textwrap
    for line in lines:
      for wrapped in textwrap.wrap(line,width=106,replace_whitespace=False) or ['']:
        d.text((24,y),wrapped,font=font,fill='#e5e7eb'); y+=26
    img.save(out/(side+'.png'))
(out/'comparison.json').write_text(json.dumps({'results':results,'identical':results['before']==results['after']},indent=2))
print(out)
print(json.dumps(results,indent=2))
