#!/bin/bash
# Keep the n8n stack alive: ollama, qdrant, n8n.
# Each check is retried once before acting, so a single blip never restarts anything.
LOG=/var/log/stack-health.log
log() { echo "$(date -Is) $*" >>"$LOG"; }

http_ok() { curl -sf -o /dev/null --max-time 6 "$1" 2>/dev/null; }

qdrant_ip() {
  docker inspect qdrant --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' 2>/dev/null | awk '{print $1}'
}

# ---------- ollama ----------
if ! http_ok http://172.18.0.1:11434/api/version; then
  sleep 5
  if ! http_ok http://172.18.0.1:11434/api/version; then
    log "ollama unhealthy -> restarting container"
    docker restart ollama >>"$LOG" 2>&1
    for i in $(seq 1 20); do
      http_ok http://172.18.0.1:11434/api/version && { log "ollama recovered after ${i}0s"; break; }
      sleep 10
    done
    # make sure the embedding model is loaded so the next query is fast
    curl -s -o /dev/null --max-time 60 -X POST http://172.18.0.1:11434/api/embeddings \
      -H 'Content-Type: application/json' -d '{"model":"bge-m3:latest","prompt":"warmup"}' 2>/dev/null
  fi
fi

# ---------- qdrant ----------
QIP=$(qdrant_ip)
if [ -n "$QIP" ] && ! http_ok "http://$QIP:6333/healthz"; then
  sleep 5
  if ! http_ok "http://$QIP:6333/healthz"; then
    log "qdrant unhealthy -> restarting container"
    docker restart qdrant >>"$LOG" 2>&1
  fi
fi

# ---------- n8n ----------
if ! docker exec n8n wget -q -T 5 -O /dev/null http://127.0.0.1:5678/healthz 2>/dev/null; then
  sleep 10
  if ! docker exec n8n wget -q -T 5 -O /dev/null http://127.0.0.1:5678/healthz 2>/dev/null; then
    log "n8n unhealthy -> restarting container"
    docker restart n8n >>"$LOG" 2>&1
  fi
fi

# ---------- proxy endpoint (the agent depends on it) ----------
if ! curl -sf -o /dev/null --max-time 8 -x http://172.19.0.1:20808 https://www.gstatic.com/generate_204 2>/dev/null; then
  log "proxy endpoint unhealthy -> handled by proxylab-watchdog"
fi
