import subprocess, json, pathlib, sys, datetime, urllib.parse, textwrap
checkout, project, output, side = sys.argv[1:]
out = pathlib.Path(output); out.mkdir(parents=True, exist_ok=True)
def cli(args):
    r = subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir','.t3'],cwd=checkout,text=True,capture_output=True)
    return {'exit':r.returncode,'stdout':r.stdout.strip(),'stderr':r.stderr.strip()}
seed = cli(['project','add',project,'--title','Link reproduction'])
launch = cli(['thread','start',project,'hello','--provider','devReplay','--model','multi-turn','--wait','--json'])
assert launch['exit']==0, launch
thread_id=json.loads(launch['stdout'])['threadId']
exact=cli(['thread','show',thread_id,'--json']); assert exact['exit']==0,exact
hosted=json.loads(exact['stdout'])['thread']['link']
env=hosted.split('/threads/')[1].split('/')[0]
deep=f't3-thread://v2/{env}/{thread_id}'
forms=[('Exact ID control',thread_id),('T3 link',deep),('Markdown link',f'[repro 38293]({deep})'),('Hosted link',hosted),('Exact ID retry',thread_id)]
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
lines=[f'{side.upper()} | {sha[:10]}','Real Node CLI -> real server /mcp | Linux | fresh isolated database','Replay: devReplay / multi-turn | synthetic project and messages','Each command: node apps/server/src/bin.ts thread show <argument>','']
results=[]
for label,arg in forms:
    r=cli(['thread','show',arg]); results.append({'label':label,'argument':arg,**r})
    lines.extend([label, f'argument: {arg}',f'exit: {r["exit"]}',r['stdout'] or r['stderr'],''])
(out/'run.json').write_text(json.dumps({'sha':sha,'launch':launch,'results':results},indent=2))
(out/'transcript.txt').write_text('\n'.join(lines))
from PIL import Image,ImageDraw,ImageFont
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
wrapped=[]
for line in lines:
    for raw in line.splitlines() or ['']:
        wrapped.extend(textwrap.wrap(raw,112,replace_whitespace=False,drop_whitespace=False) or [''])
img=Image.new('RGB',(1280,1450), '#101820'); draw=ImageDraw.Draw(img)
for i,line in enumerate(wrapped):draw.text((24,24+26*i),line,font=font,fill='#e4edf5')
img.save(out/'capture.png')
print(json.dumps({'side':side,'sha':sha,'results':results},indent=2))
