from fastapi import APIRouter
from api.connectors.prometheus import query_scalar

router = APIRouter()

CPU_AVG_QUERY = """
avg_over_time(
  100 - (
    avg by (instance) (
      rate(node_cpu_seconds_total{mode="idle"}[1m])
    ) * 100
  )
[20m])
"""

CPU_SLOPE_QUERY = """
deriv(
  100 - (
    avg by (instance) (
      rate(node_cpu_seconds_total{mode="idle"}[1m])
    ) * 100
  )
[20m])
"""

def analyze_cpu(cpu_avg: float, cpu_slope: float) -> dict:
    if cpu_avg > 90:
        status = "RISK_CPU"
        reason = "CPU très élevé"
    elif cpu_avg > 80:
        status = "WARN_CPU"
        reason = "CPU élevé"
    else:
        status = "OK"
        reason = "CPU normal"

    trend = "increasing" if cpu_slope > 0.5 else "stable"

    return {
        "status": status,
        "avg": round(cpu_avg, 2),
        "trend": trend,
        "reason": reason
    }

@router.get("/cpu")
def cpu_analysis():
    avg = query_scalar(CPU_AVG_QUERY)
    slope = query_scalar(CPU_SLOPE_QUERY)

    if avg is None or slope is None:
        return {
            "status": "UNKNOWN",
            "reason": "Prometheus data unavailable"
        }

    return analyze_cpu(avg, slope)
