from typing import Iterable

from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator

from .. import MetricsExporter


def setup_fastapi_metrics(app: FastAPI, metrics: MetricsExporter, excluded_routes: Iterable[str] | None = None) -> None:
    """
    Настраивает автоматический мониторинг HTTP запросов
    и добавляет эндпоинт /metrics.
    """
    if excluded_routes is None:
        excluded_routes = set()
    else:
        excluded_routes = set(excluded_routes)
    excluded_routes.update({"/metrics", app.docs_url, app.redoc_url, app.openapi_url})
    instrumentator = Instrumentator(
        should_group_status_codes=False,
        should_ignore_untemplated=True,
        excluded_handlers=list(excluded_routes),
        inprogress_name="http_requests_inprogress",
        inprogress_labels=True,
        registry=metrics.get_registry(),
    )

    instrumentator.instrument(app, metric_namespace=metrics.prefix)
    instrumentator.expose(app, include_in_schema=False)
