#!/bin/bash

# Script de monitoring pour MediFlash SOS+
# Usage: ./monitor.sh [--notify]

NOTIFY=${1:-false}
LOG_FILE="./monitoring.log"

# Fonction de notification (webhook ou email)
notify() {
    local message="$1"
    echo "$(date): $message" >> $LOG_FILE
    
    if [ "$NOTIFY" = "--notify" ] && [ ! -z "$MONITORING_WEBHOOK_URL" ]; then
        curl -X POST "$MONITORING_WEBHOOK_URL" \
            -H "Content-Type: application/json" \
            -d "{\"text\":\"🚨 MediFlash SOS+ Alert: $message\"}" 2>/dev/null || true
    fi
}

# Vérifier services Docker
check_services() {
    echo "🔍 Vérification des services..."
    
    SERVICES=("postgres" "backend" "frontend")
    for service in "${SERVICES[@]}"; do
        if ! docker-compose ps $service | grep -q "Up"; then
            notify "Service $service est arrêté, redémarrage en cours..."
            docker-compose restart $service
        fi
    done
}

# Vérifier health endpoints
check_health() {
    echo "🏥 Vérification health checks..."
    
    # Backend health
    if ! curl -f http://localhost:5000/api/health >/dev/null 2>&1; then
        notify "Backend health check échoué, redémarrage..."
        docker-compose restart backend
        sleep 30
    fi
    
    # Frontend health  
    if ! curl -f http://localhost:3000/health >/dev/null 2>&1; then
        notify "Frontend health check échoué, redémarrage..."
        docker-compose restart frontend
        sleep 10
    fi
}

# Vérifier espace disque
check_disk() {
    echo "💽 Vérification espace disque..."
    
    USAGE=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [ $USAGE -gt 85 ]; then
        notify "Espace disque critique: ${USAGE}%"
        
        # Nettoyage logs Docker
        docker system prune -f >/dev/null 2>&1 || true
    fi
}

# Vérifier mémoire
check_memory() {
    echo "🧠 Vérification mémoire..."
    
    USAGE=$(free | awk 'NR==2{printf "%.0f", $3*100/($3+$4)}')
    if [ $USAGE -gt 90 ]; then
        notify "Utilisation mémoire élevée: ${USAGE}%"
    fi
}

# Vérifier logs d'erreurs
check_logs() {
    echo "📋 Vérification logs d'erreurs..."
    
    ERROR_COUNT=$(docker-compose logs --since="1h" 2>/dev/null | grep -i error | wc -l)
    if [ $ERROR_COUNT -gt 10 ]; then
        notify "Nombre d'erreurs élevé dans la dernière heure: $ERROR_COUNT"
    fi
}

# Statistiques système
show_stats() {
    echo ""
    echo "📊 Statistiques système:"
    echo "   CPU: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)%"
    echo "   RAM: $(free | awk 'NR==2{printf "%.1f%%", $3*100/($3+$4)}')"
    echo "   Disque: $(df / | awk 'NR==2 {print $5}')"
    echo "   Containers: $(docker-compose ps | grep -c "Up")/$(docker-compose ps | wc -l)"
    echo ""
}

# Exécution
echo "🚀 Monitoring MediFlash SOS+ - $(date)"

check_services
check_health  
check_disk
check_memory
check_logs
show_stats

echo "✅ Monitoring terminé"