"""Alertmanager client."""

import httpx
from app.config import ALERTMANAGER_URL

_BASE = ALERTMANAGER_URL.rstrip("/")


async def get_alerts() -> list:
    """Return normalised list of active alerts from Alertmanager."""
    try:
        async with httpx.AsyncClient(timeout=5) as client:
            r = await client.get(f"{_BASE}/api/v2/alerts", params={"active": "true", "silenced": "false"})
            r.raise_for_status()
            raw = r.json()
    except Exception:
        return []

    alerts = []
    for a in raw:
        labels = a.get("labels", {})
        annotations = a.get("annotations", {})
        alerts.append({
            "name":     labels.get("alertname", "Unknown"),
            "severity": labels.get("severity", "warning"),
            "instance": labels.get("instance", ""),
            "summary":  annotations.get("summary", annotations.get("description", "")),
        })
    return alerts
