"""Minimal JSON HTTP adapter for the auth-flow proof bundle."""

from __future__ import annotations

import json
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any

from auth_core import AuthError, AuthService


class AuthHandler(BaseHTTPRequestHandler):
    service = AuthService()

    def _write(self, status: int, body: dict[str, Any]) -> None:
        encoded = json.dumps(body, separators=(",", ":")).encode()
        self.send_response(status)
        self.send_header("content-type", "application/json; charset=utf-8")
        self.send_header("cache-control", "no-store")
        self.send_header("content-length", str(len(encoded)))
        self.end_headers()
        self.wfile.write(encoded)

    def _body(self) -> dict[str, Any]:
        length = int(self.headers.get("content-length", "0"))
        if length > 16 * 1024:
            raise AuthError("request body too large")
        value = json.loads(self.rfile.read(length) or b"{}")
        if not isinstance(value, dict):
            raise AuthError("JSON object required")
        return value

    def do_POST(self) -> None:  # noqa: N802 - stdlib callback name
        try:
            body = self._body()
            if self.path == "/register":
                result = self.service.register(body.get("username"), body.get("password"))
                self._write(HTTPStatus.CREATED, result)
            elif self.path == "/login":
                result = self.service.login(body.get("username"), body.get("password"), issue_jwt=bool(body.get("issue_jwt")))
                self._write(HTTPStatus.OK, result)
            elif self.path == "/logout":
                self.service.logout(body.get("session_token"), self.headers.get("x-csrf-token", ""))
                self._write(HTTPStatus.OK, {"logged_out": True})
            else:
                self._write(HTTPStatus.NOT_FOUND, {"error": "not found"})
        except (AuthError, ValueError, TypeError, json.JSONDecodeError) as exc:
            self._write(HTTPStatus.BAD_REQUEST, {"error": str(exc)})


def serve(host: str = "127.0.0.1", port: int = 8080) -> None:
    ThreadingHTTPServer((host, port), AuthHandler).serve_forever()


if __name__ == "__main__":
    serve()
