#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

service_id() {
  compose -p argus-sys ps -q "$1"
}

wait_http() {
  local url="$1"; local attempts="${2:-120}"; local i=1
  while (( i <= attempts )); do
    if curl -fsS "$url" >/dev/null 2>&1; then return 0; fi
    echo "[..] waiting $url ($i/$attempts)"; sleep 5; ((i++))
  done
  echo "[ERR] Timeout waiting for $url" >&2; return 1
}

echo "[INFO] Waiting for ES/Kibana/Master/Fluent Bit/Bind..."

# ES (>= yellow)
attempt=1; max=120
while (( attempt <= max )); do
  if curl -fsS "http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=1s" >/dev/null 2>&1; then
    break
  fi
  echo "[..] waiting ES ($attempt/$max)"; sleep 5; ((attempt++))
done
[[ $attempt -le $max ]] || { echo "[ERR] ES not ready" >&2; exit 1; }

# Kibana: must be HTTP 200 and overall.level=available
echo "[INFO] Waiting for Kibana to be available (HTTP 200)..."
kb_attempt=1; kb_max=180
while (( kb_attempt <= kb_max )); do
  body=$(curl -sS "http://localhost:5601/api/status" 2>/dev/null || true)
  code=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:5601/api/status" || echo 000)
  if [[ "$code" == "200" ]]; then
    if echo "$body" | grep -q '"level":"available"'; then
      echo "[OK] Kibana available (HTTP 200)"
      break
    fi
  fi
  echo "[..] waiting kibana 200 ($kb_attempt/$kb_max), last_code=$code"
  sleep 5
  ((kb_attempt++))
done
if (( kb_attempt > kb_max )); then
  echo "[ERR] Kibana did not reach HTTP 200 available in time" >&2; exit 1
fi

# Master
wait_http "http://localhost:32300/readyz" 120

# Fluent Bit (host metrics on host ports)
wait_http "http://localhost:2020/api/v2/metrics" 120
wait_http "http://localhost:2021/api/v2/metrics" 120

# Bind config check
BIND_ID="$(service_id bind)"
if [[ -n "$BIND_ID" ]]; then
  docker exec "$BIND_ID" named-checkconf >/dev/null
else
  echo "[WARN] bind container id not found"
fi

echo "[OK] All services are ready"
