#!/bin/bash
set -euo pipefail

# 📁 Paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/arr_healthcheck.conf"
EXCEPTIONS_FILE="${SCRIPT_DIR}/arr_healthcheck_exceptions.conf"
KUMA_BASE_URL="https://uptime.noxs.me/api/push"
exit_code=0

# 📋 Errors storage
ALL_ERRORS=()

# 🔍 Check required tools
if ! command -v jq >/dev/null || ! command -v curl >/dev/null; then
  echo "❌ 'jq' and 'curl' are required."
  exit 2
fi

# 📄 Check config file
if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "❌ Config file '$CONFIG_FILE' not found."
  exit 2
fi

# 📄 Load ignored sources (first field only)
IGNORED_SOURCES=()
if [[ -f "$EXCEPTIONS_FILE" ]]; then
  mapfile -t IGNORED_SOURCES < <(cut -d '|' -f1 "$EXCEPTIONS_FILE" | grep -vE '^\s*#' | grep -vE '^\s*$')
fi
IGNORED_SOURCES_JSON=$(printf '%s\n' "${IGNORED_SOURCES[@]}" | jq -R . | jq -s .)

# 🔁 Main loop: name|url|api_path|api_key|kuma_push_key
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 "$(date '+%F %T') 🔍 Checking $name..."

  # 🔧 Bazarr exception
  if [[ "$name" == "bazarr" ]]; then
    response=$(curl -fsS -H "X-Api-Key: $api_key" "$full_url" || echo "")
    if [[ -z "$response" ]]; then
      echo "❌ $name: No response or connection failed"
      msg="No response"
    elif ! echo "$response" | jq -e '.' >/dev/null 2>&1; then
      echo "❌ $name: Response is not valid JSON"
      msg="Invalid JSON response"
    elif echo "$response" | jq -e 'type == "object" and .data.bazarr_version' >/dev/null 2>&1; then
      echo "✅ Bazarr is up"
      [[ -n "$kuma_key" ]] && curl -fsS "${KUMA_BASE_URL%/}/${kuma_key#/}?status=up" >/dev/null || echo "❌ Kuma push failed"
      echo
      continue
    else
      echo "❌ $name: Unexpected response format"
      msg="Unexpected response"
    fi

    msg_encoded=$(jq -rn --arg msg "$msg" '$msg|@uri')
    kuma_url="${KUMA_BASE_URL%/}/${kuma_key#/}?status=down&msg=${msg_encoded}"
    echo "➡️  [DEBUG] Kuma URL: $kuma_url"
    curl -fsS "$kuma_url" >/dev/null || echo "❌ Kuma push failed"
    exit_code=1
    ALL_ERRORS+=("$name | error | n/a | $msg")
    echo
    continue
  fi

  # 🔁 Standard healthcheck
  response=$(curl -fsS -H "X-Api-Key: $api_key" "$full_url" || echo "")

  if [[ -z "$response" ]]; then
    echo "❌ $name: No response or connection failed"
    msg="Connection failed"
    msg_encoded=$(jq -rn --arg msg "$msg" '$msg|@uri')
    kuma_url="${KUMA_BASE_URL%/}/${kuma_key#/}?status=down&msg=${msg_encoded}"
    echo "➡️  [DEBUG] Kuma URL: $kuma_url"
    curl -fsS "$kuma_url" >/dev/null || echo "❌ Kuma push failed"
    exit_code=1
    ALL_ERRORS+=("$name | error | n/a | Connection failed")
    echo
    continue
  fi

  issues=$(echo "$response" | jq --argjson ignore "$IGNORED_SOURCES_JSON" '
    map(select(.source as $src | $ignore | index($src) | not)) | length
  ' | awk '{print int($1)}')

  echo "🔎 DEBUG: issues='$issues'"

  if [[ "$issues" -eq 0 ]]; then
    echo "✅ $name is healthy or only has ignored issues"
    [[ -n "$kuma_key" ]] && curl -fsS "${KUMA_BASE_URL%/}/${kuma_key#/}?status=up" >/dev/null || echo "❌ Kuma push failed"
  else
    echo "⚠️  $name reported $issues issue(s)"

    while IFS= read -r err; do
      ALL_ERRORS+=("$name | $err")
    done < <(echo "$response" | jq --argjson ignore "$IGNORED_SOURCES_JSON" -r '
      map(select(.source as $src | $ignore | index($src) | not)) |
      .[] | "\(.type) | \(.source) | \(.message)"
    ')

    msg="${issues} issue(s)"
    msg_encoded=$(jq -rn --arg msg "$msg" '$msg|@uri')
    kuma_url="${KUMA_BASE_URL%/}/${kuma_key#/}?status=down&msg=${msg_encoded}"
    echo "➡️  [DEBUG] Kuma URL: $kuma_url"
    curl -fsS "$kuma_url" >/dev/null || echo "❌ Kuma push failed"
    exit_code=1
  fi

  echo
done < "$CONFIG_FILE"

# 📋 Print final errors summary
if [[ ${#ALL_ERRORS[@]} -gt 0 ]]; then
  echo
  echo "📋 Liste des erreurs détectées :"
  printf '🛑 %s\n' "${ALL_ERRORS[@]}"
else
  echo "✅ Aucun problème détecté sur les services monitorés."
fi

exit $exit_code