"""key_server.py - a pretend API that only answers the right key.

    python3 key_server.py

It listens on this computer only, on port 8642, answers two requests and
stops. It never sends a key back. It prints each key it was shown in its own
window, where a program inside the sandbox cannot look.
"""
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8642
RIGHT_KEY = "Bearer kru-1234-this-is-the-real-key"
REQUESTS = 2


class NotesApi(BaseHTTPRequestHandler):
    """The standard library calls do_GET for every GET request that arrives."""

    def do_GET(self):
        key = self.headers.get("Authorization", "(no key)")
        print("a request for", self.path, "came with:", key, flush=True)
        if key == RIGHT_KEY:
            self.answer(200, "The right key. Your notes: buy khao soi.\n")
        else:
            self.answer(401, "Wrong key. No notes for you.\n")

    def answer(self, status, text):
        self.send_response(status)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(text.encode())

    def log_message(self, *arguments):
        """Print nothing more: do_GET already printed what matters."""


def main():
    server = HTTPServer(("127.0.0.1", PORT), NotesApi)
    print("pretend API listening on port", PORT, flush=True)
    for _ in range(REQUESTS):
        server.handle_request()
    print("answered", REQUESTS, "requests, stopping", flush=True)


if __name__ == "__main__":
    main()
