import http.server,json,pathlib,sys,time
root=pathlib.Path(sys.argv[1]); root.mkdir(parents=True,exist_ok=True)
class Capture(http.server.BaseHTTPRequestHandler):
 def log_message(self,*a): pass
 def do_GET(self):
  data=json.dumps({'data':[]}).encode();self.send_response(200);self.end_headers();self.wfile.write(data)
 def do_POST(self):
  body=json.loads(self.rfile.read(int(self.headers.get('Content-Length',0))))
  row={'time':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'path':self.path,'originator':self.headers.get('originator'),'user-agent':self.headers.get('user-agent'),'model':body.get('model'),'structured':bool(body.get('text',{}).get('format'))}
  with (root/'requests.jsonl').open('a') as f:f.write(json.dumps(row)+'\n')
  print(json.dumps(row),flush=True)
  text=json.dumps({'title':'Rename helper function'}) if row['structured'] else 'The helper function can be renamed in utils.'
  msg={'id':'msg_capture','type':'message','role':'assistant','status':'completed','content':[{'type':'output_text','text':text,'annotations':[]}]}
  response={'id':'resp_capture','object':'response','created_at':int(time.time()),'status':'completed','model':body.get('model'),'output':[msg],'usage':{'input_tokens':1,'output_tokens':1,'total_tokens':2}}
  events=[('response.created',{'response':{**response,'status':'in_progress','output':[]}}),('response.output_item.added',{'output_index':0,'item':{**msg,'status':'in_progress','content':[]}}),('response.content_part.added',{'item_id':msg['id'],'output_index':0,'content_index':0,'part':{'type':'output_text','text':'','annotations':[]}}),('response.output_text.delta',{'item_id':msg['id'],'output_index':0,'content_index':0,'delta':text}),('response.output_text.done',{'item_id':msg['id'],'output_index':0,'content_index':0,'text':text}),('response.output_item.done',{'output_index':0,'item':msg}),('response.completed',{'response':response})]
  self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers()
  for n,(kind,data) in enumerate(events):self.wfile.write(('event: '+kind+'\ndata: '+json.dumps({'type':kind,'sequence_number':n,**data})+'\n\n').encode())
http.server.ThreadingHTTPServer(('127.0.0.1',18761),Capture).serve_forever()
