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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PRIVATE_ROOT="$TEST_ROOT/private"
API_BASE="http://localhost:31300"
NODES_JSON_PATH="$PRIVATE_ROOT/argus/metric/prometheus/nodes.json"
MASTER_DOMAIN_FILE="$PRIVATE_ROOT/argus/etc/master.argus.com"

# 等待 readyz 返回 200，确保数据库初始化完成
for _ in {1..30}; do
  status=$(curl -s -o /dev/null -w '%{http_code}' "$API_BASE/readyz" || true)
  if [[ "$status" == "200" ]]; then
    break
  fi
  sleep 1
 done

if [[ "${status:-}" != "200" ]]; then
  echo "[ERROR] /readyz 未在预期时间内返回 200，实际=$status" >&2
  exit 1
fi

echo "[INFO] /readyz 已通过，就绪检查成功"

# scheduler 启动时会产生空的 nodes.json，这里等待文件出现并校验内容
for _ in {1..30}; do
  if [[ -f "$NODES_JSON_PATH" ]]; then
    break
  fi
  sleep 1
 done

if [[ ! -f "$NODES_JSON_PATH" ]]; then
  echo "[ERROR] 未在预期时间内生成 $NODES_JSON_PATH" >&2
  exit 1
fi

if ! python3 - "$NODES_JSON_PATH" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    data = json.load(handle)
if data != []:
    raise SystemExit(f"nodes.json initial content should be [], got {data}")
PY
then
  echo "[ERROR] nodes.json 初始内容不是空数组" >&2
  exit 1
fi

echo "[INFO] nodes.json 初始状态校验通过"

# 中文提示：输出 master 写入的域名文件，失败不影响测试
if [[ -f "$MASTER_DOMAIN_FILE" ]]; then
  MASTER_IP=$(<"$MASTER_DOMAIN_FILE")
  echo "[INFO] master.argus.com 记录: $MASTER_IP"
else
  echo "[WARN] 未找到 master.argus.com 记录文件，目录=$MASTER_DOMAIN_FILE"
fi
