"""Prometheus metrics (build plan Section 8).

Counters/histograms are module-level (registered once). A middleware records
request count + latency by route template; ``/metrics`` exposes them.
"""

from __future__ import annotations

import time

from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
from starlette.requests import Request
from starlette.responses import Response

HTTP_REQUESTS = Counter(
    "legate_http_requests_total",
    "Total HTTP requests.",
    ["method", "path", "status"],
)
HTTP_LATENCY = Histogram(
    "legate_http_request_duration_seconds",
    "HTTP request latency in seconds.",
    ["method", "path"],
)
RUNS_STARTED = Counter(
    "legate_runs_started_total",
    "Agent and workflow runs started.",
    ["kind"],
)


def record_run_started(kind: str) -> None:
    RUNS_STARTED.labels(kind=kind).inc()


async def metrics_middleware(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    route = request.scope.get("route")
    path = getattr(route, "path", None) or "unmatched"
    method = request.method
    HTTP_LATENCY.labels(method=method, path=path).observe(time.perf_counter() - start)
    HTTP_REQUESTS.labels(method=method, path=path, status=str(response.status_code)).inc()
    return response


def metrics_endpoint() -> Response:
    return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
