import logging
from datetime import datetime
from typing import Any

import pytz
import tornado
from tornado import httputil
from tornado.web import Application

from core.prometheus_metrics_handler import api_requests_counter
from core.utils import safe_json_dumps


class APIStatusHandler(tornado.web.RequestHandler):
    """API request handler for /api/v2/status"""

    def __init__(self, application: "Application", request: httputil.HTTPServerRequest, **kwargs: Any):
        self._status_data = None
        self._web_server_metrics = None
        super().__init__(application, request, **kwargs)

    def initialize(self, status_data, web_server_metrics):
        self._status_data = status_data
        self._web_server_metrics = web_server_metrics

    def get(self):
        try:
            # Metrics
            self._web_server_metrics["last_api_access_time"] = datetime.now(pytz.UTC)
            self._web_server_metrics["api_access_counter"] += 1
            self._web_server_metrics["status"] = "OK"
            api_requests_counter.inc()

            self.write(safe_json_dumps(self._status_data))
            self.set_status(200)
            self.set_header("Cache-Control", "no-store")
            self.set_header("Content-Type", "application/json")

        except Exception as e:
            logging.error("Exception when handling client request to status API: %s", e, exc_info=True)
            self.write(safe_json_dumps("Error - an internal server error occurred."))
            self.set_status(500)
