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

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

API_BASE="http://localhost:32300/api/v1/master"

HOST_A="dev-yyrshare-nbnyx10-cp2f-pod-0"
HOST_B="dev-yyrshare-uuuu10-ep2f-pod-0"

HEALTH_A="$TEST_ROOT/private-nodea/argus/agent/$HOST_A/health"
HEALTH_B="$TEST_ROOT/private-nodeb/argus/agent/$HOST_B/health"

write_health() {
  local dir="$1"; mkdir -p "$dir"
  cat > "$dir/log-fluentbit.json" <<JSON
{ "status": "healthy", "timestamp": "2024-10-05T12:05:00Z" }
JSON
  cat > "$dir/metric-node-exporter.json" <<JSON
{ "status": "healthy", "timestamp": "2024-10-05T12:05:00Z" }
JSON
}

echo "[INFO] Writing health files for both nodes..."
write_health "$HEALTH_A"
write_health "$HEALTH_B"

ID_A="$(cat "$TMP_DIR/node_id_a")"
ID_B="$(cat "$TMP_DIR/node_id_b")"

check_health() {
  local id="$1"; local tries=40
  for _ in $(seq 1 $tries); do
    sleep 2
    resp=$(curl -fsS "$API_BASE/nodes/$id" 2>/dev/null || true)
    [[ -z "$resp" ]] && continue
    echo "$resp" > "$TMP_DIR/node_${id}_detail.json"
    if python3 - "$TMP_DIR/node_${id}_detail.json" <<'PY'
import json,sys
node=json.load(open(sys.argv[1]))
h=node.get("health",{})
sys.exit(0 if ("log-fluentbit" in h and "metric-node-exporter" in h) else 1)
PY
    then return 0; fi
  done
  return 1
}

check_health "$ID_A" || { echo "[ERR] health keys not reported for node A" >&2; exit 1; }
check_health "$ID_B" || { echo "[ERR] health keys not reported for node B" >&2; exit 1; }

NODES_JSON="$TEST_ROOT/private/argus/metric/prometheus/nodes.json"
if [[ ! -f "$NODES_JSON" ]]; then
  echo "[ERR] nodes.json missing at $NODES_JSON" >&2; exit 1
fi

python3 - "$NODES_JSON" <<'PY'
import json,sys
with open(sys.argv[1]) as h:
  nodes=json.load(h)
assert isinstance(nodes,list)
assert len(nodes) == 2, f"expected 2 nodes online, got {len(nodes)}"
PY

echo "[OK] Health reported and nodes.json has 2 online nodes"
