"""Standalone HTTP server for customers without an existing web framework.

Usage::

    pillar.serve(port=8787)
"""
from __future__ import annotations

import asyncio
import json
import logging
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from pillar._client import Pillar

logger = logging.getLogger("pillar")


def run_server(pillar: Pillar, *, host: str = "0.0.0.0", port: int = 8787) -> None:
    """Start a blocking HTTP server that dispatches all POSTs to *pillar*."""

    class Handler(BaseHTTPRequestHandler):
        def do_POST(self) -> None:
            content_length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(content_length)
            headers = {
                "X-Pillar-Signature": self.headers.get("X-Pillar-Signature", ""),
            }

            result, status_code = asyncio.run(pillar.handle(body, headers))
            response_body = json.dumps(result).encode()

            self.send_response(status_code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(response_body)))
            self.end_headers()
            self.wfile.write(response_body)

        def log_message(self, format: str, *args: object) -> None:
            logger.debug(format, *args)

    server = HTTPServer((host, port), Handler)
    logger.info("Pillar standalone server listening on %s:%d", host, port)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        logger.info("Shutting down Pillar standalone server")
        server.shutdown()
