"""Prometheus metrics for NCS."""
import logging

logger = logging.getLogger("ncs_prom")

try:
    from prometheus_client import Gauge, CollectorRegistry, generate_latest
    PROM_AVAILABLE = True
    REGISTRY = CollectorRegistry()

    runtime_health = Gauge(
        "ncs_runtime_health", "Runtime health (1=ok, 0=down)",
        ["runtime"], registry=REGISTRY,
    )
    runtime_p50 = Gauge(
        "ncs_runtime_p50_ms", "Runtime p50 latency",
        ["runtime"], registry=REGISTRY,
    )
    runtime_p95 = Gauge(
        "ncs_runtime_p95_ms", "Runtime p95 latency",
        ["runtime"], registry=REGISTRY,
    )
    node_wait = Gauge(
        "ncs_node_wait_ms", "Estimated wait for node",
        registry=REGISTRY,
    )

except ImportError:
    PROM_AVAILABLE = False
    REGISTRY = None


def update_from_caps(caps: dict):
    if not PROM_AVAILABLE:
        return
    nl = caps.get("node_load", {})
    node_wait.set(nl.get("estimated_wait_ms", 0))
    for rl in caps.get("runtime_load", []):
        rt = rl.get("runtime", "?")
        runtime_health.labels(runtime=rt).set(1 if rl.get("healthy") else 0)
        if rl.get("p50_ms") is not None:
            runtime_p50.labels(runtime=rt).set(rl["p50_ms"])
        if rl.get("p95_ms") is not None:
            runtime_p95.labels(runtime=rt).set(rl["p95_ms"])


def get_metrics_text():
    if PROM_AVAILABLE and REGISTRY:
        return generate_latest(REGISTRY)
    return None
