"""A minimal webhook receiver using only the standard library and the Kernsignal SDK.

    export KERNSIGNAL_WEBHOOK_SECRET=whsec_...      # shown once when you create the endpoint
    python webhook_receiver.py 8080

Put it behind HTTPS (a reverse proxy or a tunnel); Kernsignal only delivers to https:// URLs.
"""
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

from kernsignal import SignatureVerificationError, construct_event

SECRET = os.environ["KERNSIGNAL_WEBHOOK_SECRET"]
seen = set()   # use a database in production: the same event id can arrive more than once


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))   # the raw bytes, not parsed JSON
        try:
            event = construct_event(raw, self.headers.get("Kernsignal-Signature"), SECRET)
        except SignatureVerificationError as exc:
            self.send_response(400)
            self.end_headers()
            self.wfile.write(str(exc).encode())
            return
        if event["id"] not in seen:
            seen.add(event["id"])
            audit = event["data"]["object"]
            print(f"{event['type']}: {audit['id']} is {audit['status']}")
        self.send_response(200)   # answer 2xx quickly; do slow work after responding
        self.end_headers()

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    HTTPServer(("0.0.0.0", int(sys.argv[1]) if len(sys.argv) > 1 else 8080), Handler).serve_forever()
