"""Prometheus Node Exporter target discovery.

The backend owns the list of remote Node Exporter targets so that operators can
enable scraping per machine from the Manage UI. The list is exposed over HTTP at
``GET /api/monitoring/prometheus-targets`` and consumed by an external Prometheus
via ``http_sd_configs`` (no shared volume required).
"""

from __future__ import annotations

import logging
from typing import Any

from media_library_viewer_api.services.settings_store import SettingsStore

logger = logging.getLogger(__name__)

DEFAULT_NODE_EXPORTER_PORT = 9100


def _scrape_address(machine: dict[str, Any]) -> str | None:
    """Return host:port for the Node Exporter on a machine, or None if disabled."""
    if not machine.get("node_exporter_enabled"):
        return None
    scrape_host = str(machine.get("node_exporter_scrape_host") or "").strip()
    host = scrape_host or str(machine.get("host") or "").strip()
    if not host or host == "localhost":
        return None
    port = int(machine.get("node_exporter_port") or DEFAULT_NODE_EXPORTER_PORT)
    return f"{host}:{port}"


def build_node_exporter_targets(store: SettingsStore) -> list[dict[str, Any]]:
    """Build an http-SD target list for all enabled SSH machines.

    Local machines are excluded because the Docker host is scraped directly.
    """
    targets: list[dict[str, Any]] = []
    for machine in store.list_machines():
        if not machine.get("enabled"):
            continue
        if str(machine.get("mode") or "local").strip().lower() != "ssh":
            continue
        address = _scrape_address(machine)
        if not address:
            continue
        targets.append(
            {
                "targets": [address],
                "labels": {
                    "job": "node-exporter-remote",
                    "machine_id": str(machine.get("id") or ""),
                    "machine_name": str(machine.get("name") or ""),
                    "instance": address,
                },
            }
        )
    return targets
