#!/bin/bash
# Service Health Check — updates dashboard status
# Run manually or via heartbeat

DASHBOARD="http://localhost:9200"
ALL_OK=true

check_service() {
    local name="$1"
    local check="$2"
    local result
    result=$(eval "$check" 2>&1)
    local rc=$?
    if [ $rc -eq 0 ]; then
        echo "✅ $name"
    else
        echo "❌ $name: $result"
        ALL_OK=false
    fi
}

check_http() {
    local name="$1"
    local url="$2"
    local code
    code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>&1)
    if [[ "$code" =~ ^(200|301|302)$ ]]; then
        echo "✅ $name (HTTP $code)"
    else
        echo "❌ $name (HTTP $code)"
        ALL_OK=false
    fi
}

echo "=== Service Health Check ($(date -u +%Y-%m-%dT%H:%M:%SZ)) ==="

# Systemd services
check_service "Proton Bridge" "systemctl --user is-active protonmail-bridge"
check_service "Mail Bridge" "systemctl --user is-active mail-bridge"
check_service "Message Bridge" "systemctl --user is-active message-bridge"

# HTTP endpoints
check_http "Mail Bridge API" "http://localhost:8025/health"
check_http "Dashboard" "$DASHBOARD/api/tasks"
check_http "Zurich VPS" "https://zurich.inou.com"
check_http "inou.com" "https://inou.com"

# Disk space
DISK_PCT=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$DISK_PCT" -gt 85 ]; then
    echo "⚠️  Disk: ${DISK_PCT}% used"
    ALL_OK=false
else
    echo "✅ Disk: ${DISK_PCT}% used"
fi

# Memory
MEM_PCT=$(free | awk '/Mem:/ {printf "%.0f", $3/$2*100}')
if [ "$MEM_PCT" -gt 90 ]; then
    echo "⚠️  Memory: ${MEM_PCT}% used"
    ALL_OK=false
else
    echo "✅ Memory: ${MEM_PCT}% used"
fi

# Load average
LOAD=$(cat /proc/loadavg | awk '{print $1}')
CORES=$(nproc)
LOAD_INT=${LOAD%.*}
if [ "${LOAD_INT:-0}" -gt "$CORES" ]; then
    echo "⚠️  Load: $LOAD ($CORES cores)"
    ALL_OK=false
else
    echo "✅ Load: $LOAD ($CORES cores)"
fi

echo ""
if $ALL_OK; then
    echo "Overall: ALL SYSTEMS HEALTHY ✅"
    # Update dashboard
    curl -s -X POST "$DASHBOARD/api/status" -H 'Content-Type: application/json' \
      -d "{\"key\":\"services\",\"value\":\"All services healthy ✅ (checked $(date -u +%H:%M) UTC)\",\"type\":\"info\"}" > /dev/null
else
    echo "Overall: ISSUES DETECTED ⚠️"
    curl -s -X POST "$DASHBOARD/api/status" -H 'Content-Type: application/json' \
      -d "{\"key\":\"services\",\"value\":\"Issues detected ⚠️ — check logs\",\"type\":\"warning\"}" > /dev/null
fi
