#!/bin/bash
URL="${APP_URL:-http://localhost:8080/health}"
INTERVAL="${CHECK_INTERVAL:-30}"
LOG_FILE="${LOG_FILE:-monitor.log}"
ALERT_FILE="${ALERT_FILE:-alerts.log}"
METRICS_JSON="${METRICS_JSON:-metrics.json}"   
MAX_TIMEOUT=5

echo "🔍 بدء المراقبة على: $URL  (كل ${INTERVAL}s) — اضغط Ctrl+C للإيقاف"

while true; do
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

    START_NS=$(date +%s%N)
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time "$MAX_TIMEOUT" "$URL")
    CURL_EXIT=$?
    END_NS=$(date +%s%N)
    RESPONSE_MS=$(( (END_NS - START_NS) / 1000000 ))

    if [ "$CURL_EXIT" -eq 0 ] && [ "$HTTP_CODE" == "200" ]; then
        STATUS="UP"
    else
        STATUS="DOWN"
    fi

    LINE="$TIMESTAMP | status=$STATUS | http_code=$HTTP_CODE | response_ms=$RESPONSE_MS"
    echo "$LINE"
    echo "$LINE" >> "$LOG_FILE"

    
    if [ "$STATUS" == "DOWN" ]; then
        echo "🚨 $TIMESTAMP ALERT: الخدمة غير متاحة (http_code=$HTTP_CODE)" | tee -a "$ALERT_FILE"
    fi

    cat > "$METRICS_JSON" <<EOF
{
  "timestamp": "$TIMESTAMP",
  "status": "$STATUS",
  "http_code": "$HTTP_CODE",
  "response_ms": $RESPONSE_MS
}
EOF

    sleep "$INTERVAL"
done
