"""Constructed local study application. Marker data and credentials are public."""
import json
import sqlite3
from http.server import BaseHTTPRequestHandler, HTTPServer

from auth import authenticate
from repository import lookup


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        actor = authenticate(self.headers.get("Authorization", ""))
        if actor is None:
            self.reply(401, {"error": "authentication required"})
            return
        if not self.path.startswith("/records/"):
            self.reply(404, {"error": "not found"})
            return
        record_id = self.path.removeprefix("/records/")
        db = sqlite3.connect(":memory:")
        db.execute("CREATE TABLE records (id TEXT, tenant TEXT, value TEXT)")
        db.executemany("INSERT INTO records VALUES (?, ?, ?)", [
            ("r1", "tenant-one", "public-marker-one"),
            ("r2", "tenant-two", "public-marker-two"),
        ])
        try:
            row = lookup(db, record_id, actor["tenant"])
        finally:
            db.close()
        self.reply(200, {"value": row[0]}) if row else self.reply(404, {"error": "not found"})

    def reply(self, status, body):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *_args):
        pass


if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", 0), Handler)
    print(json.dumps({"port": server.server_port}), flush=True)
    server.serve_forever()
