#!/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"

mkdir -p "$TMP_DIR"

echo "[INFO] Waiting for agent nodes to register..."

extract_node() {
  local name="$1"; local output="$2"; local json_file="$3"
  python3 - "$name" "$output" "$json_file" <<'PY'
import json, sys, pathlib
name = sys.argv[1]
out = pathlib.Path(sys.argv[2])
json_file = sys.argv[3]
with open(json_file, 'r') as fh:
    data = json.load(fh)
node = next((n for n in data if n.get("name") == name), None)
if node:
    out.write_text(node["id"])  # save id
    print(node["id"])           # also print for shell capture
PY
}

ID_A=""; ID_B=""
for _ in {1..60}; do
  sleep 2
  resp=$(curl -fsS "$API_BASE/nodes" 2>/dev/null || true)
  if [[ -z "$resp" ]]; then
    continue
  fi
  # only try to parse when it's a JSON array
  if ! echo "$resp" | head -c1 | grep -q '\['; then
    continue
  fi
  echo "$resp" > "$TMP_DIR/nodes_list.json"
  ID_A=$(extract_node "$HOST_A" "$TMP_DIR/node_id_a" "$TMP_DIR/nodes_list.json" 2>/dev/null || true)
  ID_B=$(extract_node "$HOST_B" "$TMP_DIR/node_id_b" "$TMP_DIR/nodes_list.json" 2>/dev/null || true)
  if [[ -s "$TMP_DIR/node_id_a" && -s "$TMP_DIR/node_id_b" ]]; then
    break
  fi
done

# 若仍未全部注册，尝试重启 node-b 并再等待一轮（兼容 DNS/启动时序抖动）
if [[ ! -s "$TMP_DIR/node_id_a" || ! -s "$TMP_DIR/node_id_b" ]]; then
  echo "[WARN] node-a or node-b not registered in first window; restarting node-b and retrying..." >&2
  # 仅重启 node-b，避免影响 es/kibana/master
  if docker ps --format '{{.Names}}' | grep -q '^argus-node-b$'; then
    docker restart argus-node-b >/dev/null 2>&1 || true
  fi
  # 再等待一轮（最多 120 秒）
  > "$TMP_DIR/node_id_b"
  for _ in {1..60}; do
    sleep 2
    resp=$(curl -fsS "$API_BASE/nodes" 2>/dev/null || true)
    [[ -z "$resp" ]] && continue
    if ! echo "$resp" | head -c1 | grep -q '\['; then
      continue
    fi
    echo "$resp" > "$TMP_DIR/nodes_list.json"
    ID_A=$(extract_node "$HOST_A" "$TMP_DIR/node_id_a" "$TMP_DIR/nodes_list.json" 2>/dev/null || true)
    ID_B=$(extract_node "$HOST_B" "$TMP_DIR/node_id_b" "$TMP_DIR/nodes_list.json" 2>/dev/null || true)
    if [[ -s "$TMP_DIR/node_id_a" && -s "$TMP_DIR/node_id_b" ]]; then
      break
    fi
  done
fi

if [[ ! -s "$TMP_DIR/node_id_a" || ! -s "$TMP_DIR/node_id_b" ]]; then
  echo "[ERR] Agents did not register in time (after retry)" >&2
  echo "[HINT] Current /nodes response:" >&2
  sed -n '1,200p' "$TMP_DIR/nodes_list.json" >&2 || true
  exit 1
fi

node_detail() {
  local id="$1"; local out="$2"
  curl -fsS "$API_BASE/nodes/$id" -o "$out"
}

node_detail "$(cat "$TMP_DIR/node_id_a")" "$TMP_DIR/detail_a.json"
node_detail "$(cat "$TMP_DIR/node_id_b")" "$TMP_DIR/detail_b.json"

python3 - "$TMP_DIR/detail_a.json" "$TMP_DIR/initial_ip_a" <<'PY'
import json, sys, pathlib
node=json.load(open(sys.argv[1]))
ip=node.get("meta_data",{}).get("ip")
assert ip, "missing ip"
pathlib.Path(sys.argv[2]).write_text(ip)
PY

python3 - "$TMP_DIR/detail_b.json" "$TMP_DIR/initial_ip_b" <<'PY'
import json, sys, pathlib
node=json.load(open(sys.argv[1]))
ip=node.get("meta_data",{}).get("ip")
assert ip, "missing ip"
pathlib.Path(sys.argv[2]).write_text(ip)
PY

NODE_JSON_A="$TEST_ROOT/private-nodea/argus/agent/$HOST_A/node.json"
NODE_JSON_B="$TEST_ROOT/private-nodeb/argus/agent/$HOST_B/node.json"

[[ -f "$NODE_JSON_A" ]] || { echo "[ERR] node.json missing for $HOST_A" >&2; exit 1; }
[[ -f "$NODE_JSON_B" ]] || { echo "[ERR] node.json missing for $HOST_B" >&2; exit 1; }

echo "[OK] Agents registered: $(cat "$TMP_DIR/node_id_a") , $(cat "$TMP_DIR/node_id_b")"
