import http.server,json,time
from pathlib import Path
ROOT=Path(__file__).parent
class Handler(http.server.BaseHTTPRequestHandler):
 def do_POST(self):
  self.rfile.read(int(self.headers.get('content-length',0)))
  reset=json.loads((ROOT/'deadline.json').read_text())["reset"]
  limited=time.time()<reset and not self.path.startswith('/success')
  with (ROOT/'upstream-requests.jsonl').open('a') as f:
   f.write(json.dumps({"at":time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),"status":429 if limited else 200,"reset":reset})+'\n')
  if limited:
   body=json.dumps({"error":{"type":"usage_limit_reached","code":"usage_limit_reached","message":"Usage limit reached","plan_type":"plus","resets_at":reset,"resets_in_seconds":max(1,reset-int(time.time()))}}).encode()
   self.send_response(429); self.send_header('Content-Type','application/json'); self.end_headers(); self.wfile.write(body)
  else:
   self.send_response(200); self.send_header('Content-Type','text/event-stream'); self.end_headers()
   item={"id":"msg_demo","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Hello! The usage limit has reset.","annotations":[]}]}
   events=[{"type":"response.created","response":{"id":"resp_demo","status":"in_progress","output":[]}},
    {"type":"response.output_item.added","output_index":0,"item":{**item,"status":"in_progress","content":[]}},
    {"type":"response.content_part.added","item_id":"msg_demo","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}},
    {"type":"response.output_text.delta","item_id":"msg_demo","output_index":0,"content_index":0,"delta":"Hello! The usage limit has reset."},
    {"type":"response.output_text.done","item_id":"msg_demo","output_index":0,"content_index":0,"text":"Hello! The usage limit has reset."},
    {"type":"response.output_item.done","output_index":0,"item":item},
    {"type":"response.completed","response":{"id":"resp_demo","status":"completed","output":[item],"usage":{"input_tokens":1,"output_tokens":8,"total_tokens":9}}}]
   for event in events:
    self.wfile.write(('event: '+event['type']+'\ndata: '+json.dumps(event)+'\n\n').encode()); self.wfile.flush()
 def do_GET(self):
  self.send_response(200); self.send_header('Content-Type','application/json'); self.end_headers(); self.wfile.write(b'{"data":[]}')
http.server.HTTPServer(('127.0.0.1',18788),Handler).serve_forever()
