import http.server,urllib.request,urllib.error,json,time,threading
rows=[]; last=0
class Proxy(http.server.BaseHTTPRequestHandler):
 def log_message(self,*a):pass
 def do_GET(self):self.forward()
 def do_POST(self):self.forward()
 def forward(self):
  global last,rows
  if self.path.startswith('/_evidence'):
   if self.path.endswith('/reset'):rows=[]
   if self.path.endswith('/settled'):
    start=time.time()
    while (not rows or time.time()-last<3) and time.time()-start<45:time.sleep(.1)
   data=json.dumps(rows).encode();self.send_response(200);self.end_headers();self.wfile.write(data);return
  body=self.rfile.read(int(self.headers.get('Content-Length',0))) or None
  headers={k:v for k,v in self.headers.items() if k.lower() not in ['host','connection','content-length']}
  req=urllib.request.Request('http://127.0.0.1:19351'+self.path,data=body,headers=headers,method=self.command)
  try:r=urllib.request.urlopen(req)
  except urllib.error.HTTPError as e:r=e
  data=r.read()
  if '/pulls?' in self.path:
   try:count=len(json.loads(data))
   except:count=-1
   rows.append({'path':self.path,'status':r.status,'items':count});last=time.time()
  self.send_response(r.status)
  for k,v in r.headers.items():
   if k.lower() not in ['transfer-encoding','connection','content-length']:self.send_header(k,v)
  self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
http.server.ThreadingHTTPServer(('127.0.0.1',19352),Proxy).serve_forever()
