from fastapi import APIRouter
from api.correlation.collectors import collect_metrics
from api.correlation.engine import evaluate, RULES
from api.llm.client import explain_incident

router = APIRouter()


@router.get("/alerts")
def alerts():
    metrics = collect_metrics()

    # Récupère la liste de règles depuis RULES ; fallback sur [] si introuvable
    rules_list = []
    if isinstance(RULES, dict):
        rules_list = RULES.get("rules", []) or []
    elif isinstance(RULES, list):
        rules_list = RULES

    incidents = evaluate(rules_list, metrics)

    if not incidents:
        return {"status": "ok"}

    for incident in incidents:
        # explain_incident doit être résilient — voir api/llm/client.py pour fallback
        incident["summary"] = explain_incident(incident, metrics)

    return {
        "status": "incident",
        "incidents": incidents,
    }
