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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TMP_ROOT="$TEST_ROOT/tmp"
API_BASE="http://localhost:32300/api/v1/master"
NODE_ID="$(cat "$TMP_ROOT/node_id")"
NODES_JSON="$TEST_ROOT/private/argus/metric/prometheus/nodes.json"

success=false
detail_file="$TMP_ROOT/agent_status_detail.json"
for _ in {1..20}; do
  sleep 2
  if ! curl -sS "$API_BASE/nodes/$NODE_ID" -o "$detail_file"; then
    continue
  fi
  if python3 - "$detail_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)
if node["status"] != "online":
    raise SystemExit(1)
health = node.get("health", {})
if "log-fluentbit" not in health or "metric-node-exporter" not in health:
    raise SystemExit(1)
PY
  then
    success=true
    break
  fi
done

if [[ "$success" != true ]]; then
  echo "[ERROR] Node did not report health data in time" >&2
  exit 1
fi

if [[ ! -f "$NODES_JSON" ]]; then
  echo "[ERROR] nodes.json missing at $NODES_JSON" >&2
  exit 1
fi

python3 - "$NODES_JSON" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    nodes = json.load(handle)
assert len(nodes) == 1, nodes
entry = nodes[0]
assert entry["node_id"], entry
PY

echo "[INFO] Master reflects agent health and nodes.json entries"
