"""Prints every POST it receives. Test aid for the Tabby simulator's webhooks (not part of the repo).

  python3 tabby_webhook_receiver.py 9099

Answers by path:  /ok -> 200   /created -> 201   /fail -> 500   /slow -> 200 after 70 s (past the 60 s timeout)
Prints the time, path, the X-Sign header (the custom header used in the tests) and the JSON body.
"""
import json, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

CODES = {"/ok": 200, "/created": 201, "/fail": 500}


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("content-length", 0))).decode()
        try:
            body = json.dumps(json.loads(body), separators=(",", ":"))
        except ValueError:
            pass
        print(time.strftime("%H:%M:%S"), "POST", self.path, "| X-Sign:", self.headers.get("X-Sign"), "|", body, flush=True)
        if self.path == "/slow":
            time.sleep(70)
        self.send_response(CODES.get(self.path, 200))
        self.send_header("content-length", "0")
        self.end_headers()

    def log_message(self, *args):
        pass


port = int(sys.argv[1]) if len(sys.argv) > 1 else 9099
print("listening on", port, "- /ok 200, /created 201, /fail 500, /slow 200 after 70 s", flush=True)
ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()
