#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/arr_healthcheck.conf"
OUTPUT_FILE="$SCRIPT_DIR/arr_healthcheck_errors.csv"

# 🧪 Vérifie si le fichier existe et contient une en-tête correcte
if [[ ! -f "$OUTPUT_FILE" ]] || ! head -n 1 "$OUTPUT_FILE" | grep -q '^timestamp,app,level,source,message$'; then
  echo "timestamp,app,level,source,message" > "$OUTPUT_FILE"
fi

# 🔍 Vérifie les outils requis
command -v curl >/dev/null || { echo "❌ curl requis"; exit 1; }
command -v jq >/dev/null || { echo "❌ jq requis"; exit 1; }
[[ -f "$CONFIG_FILE" ]] || { echo "❌ Fichier conf manquant : $CONFIG_FILE"; exit 1; }

# 🔁 Lecture de la configuration
while IFS="|" read -r name url api_path api_key kuma_key || [[ -n "${name:-}" ]]; do
  [[ -z "$name" || "$name" =~ ^# ]] && continue

  full_url="${url}${api_path}"
  echo "🔍 Checking $full_url..."

  response=$(curl -fsS -H "X-Api-Key: $api_key" "$full_url") || {
    echo "❌ Erreur API pour $full_url"
    continue
  }

  timestamp=$(date '+%F %T')

  echo "$response" | jq -c '.[]' | while read -r item; do
    level=$(echo "$item" | jq -r '.type')
    source=$(echo "$item" | jq -r '.source // "N/A"')
    message=$(echo "$item" | jq -r '.message')
    echo "$timestamp,$name,$level,$source,\"$message\"" >> "$OUTPUT_FILE"
  done
done < "$CONFIG_FILE"

echo "✅ Rapport mis à jour : $OUTPUT_FILE"