#!/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")"
ENV_NODE_ID="$(cat "$TMP_ROOT/node_id_host_abc")"
ENV_HOSTNAME="host_abc"
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" "$NODE_ID" "$ENV_NODE_ID" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    nodes = json.load(handle)

expected_primary = sys.argv[2]
expected_env = sys.argv[3]

ids = {entry.get("node_id") for entry in nodes}
assert expected_primary in ids, nodes
assert expected_env in ids, nodes
assert len(nodes) >= 2, nodes
PY

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

env_detail_file="$TMP_ROOT/env_agent_detail.json"
curl -sS "$API_BASE/nodes/$ENV_NODE_ID" -o "$env_detail_file"
python3 - "$env_detail_file" "$ENV_HOSTNAME" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)

expected_name = sys.argv[2]

assert node.get("name") == expected_name, node
meta = node.get("meta_data", {})
assert meta.get("env") == "prod", meta
assert meta.get("user") == "ml", meta
assert meta.get("instance") == "node-3", meta
PY

echo "[INFO] Env-variable agent reports expected metadata"
