from prometheus_client import start_http_server, Summary
from http.server import HTTPServer, BaseHTTPRequestHandler
import json


# Define the metrics.
HTTP_REQUEST_DURATION_TOTAL = Summary('http_request_duration_total', 'Total time spent processing requests.')


class RequestHandler(BaseHTTPRequestHandler):
    """
    Class responsible for handling the requests. Implements only the GET method, simply prints out
    the request information.
    """
    @HTTP_REQUEST_DURATION_TOTAL.time()
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps({
            'command': self.command,
            'path': self.path,
            'request_version': self.request_version,
        }).encode())


def run_server(bind_address='', bind_port=8080):
    server = HTTPServer((bind_address, bind_port), RequestHandler)
    server.serve_forever()


def main() -> None:
    """
    Main entry-point for the application. Starts the prometheus server for serving the metrics,
    then starts a very simple
    """
    # Start prometheus metrics server.
    start_http_server(9901)
    # Run the application server.
    run_server()


if __name__ == '__main__':
    main()
