import datetime, json, pathlib, sys, urllib.request, uuid, websocket

side=sys.argv[1]
root=pathlib.Path('/tmp/lead-25847-r1/evidence-capture')
run=root/('seed-run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%f'))
run.mkdir()
port={'before':16001,'after':14380}[side]
origin=f'http://127.0.0.1:{port}'
token=(root/f'token-{side}.txt').read_text().strip().splitlines()[-1]
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json','x-t3-orchestration-protocol':'2'}
def http(path,data=None):
    req=urllib.request.Request(origin+path,data=json.dumps(data).encode() if data is not None else None,headers=headers)
    with urllib.request.urlopen(req) as response:return json.load(response)
descriptor=http('/.well-known/t3/environment')
workspace=root/'synthetic-workspace'
workspace.mkdir(exist_ok=True)
project='evidence-25847-project'
thread='evidence-25847-thread'
http('/api/projects/mutate',dict(type='project.create',commandId=str(uuid.uuid4()),projectId=project,title='Keyboard repair evidence',workspaceRoot=str(workspace)))
ticket=http('/api/auth/websocket-ticket',{})['ticket']
ws=websocket.create_connection(f'ws://127.0.0.1:{port}/ws?orchestrationProtocol=2&wsTicket={ticket}',origin=origin,timeout=30)
command=dict(type='thread.create',commandId=str(uuid.uuid4()),threadId=thread,projectId=project,title='Keyboard repair fixture',modelSelection={'instanceId':'codex','model':'gpt-5.4'},runtimeMode='full-access',interactionMode='default',branch=None,worktreePath=None,createdBy='user',creationSource='mobile')
ws.send(json.dumps({'_tag':'Request','id':'1','tag':'orchestration.dispatchCommand','payload':command,'headers':[]}))
while True:
    packet=json.loads(ws.recv())
    print(json.dumps(packet))
    entries=packet if isinstance(packet,list) else [packet]
    if any(str(x.get('requestId'))=='1' and x.get('_tag')=='Exit' for x in entries):break
ws.close()
result={'environmentId':descriptor['environmentId'],'projectId':project,'threadId':thread,'workspace':str(workspace),'port':port}
(run/f'seed-{side}.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result))
