#!/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"
TMP_ROOT="$TEST_ROOT/tmp"
API_BASE="http://localhost:31300/api/v1/master"

# 注册第二个节点 A2（保持在线）
second_payload=$(cat <<'JSON'
{
  "name": "dev-testuser-testinst-pod-1",
  "type": "agent",
  "meta_data": {
    "hostname": "dev-testuser-testinst-pod-1",
    "ip": "10.0.0.11",
    "env": "dev",
    "user": "testuser",
    "instance": "testinst",
    "cpu_number": 8,
    "memory_in_bytes": 2147483648,
    "gpu_number": 0
  },
  "version": "1.1.0"
}
JSON
)

status=$(curl -sS -o "$TMP_ROOT/second_register.json" -w '%{http_code}' -H 'Content-Type: application/json' -X POST "$API_BASE/nodes" -d "$second_payload")
if [[ "$status" != "201" ]]; then
  echo "[ERROR] Second node registration failed: $status" >&2
  cat "$TMP_ROOT/second_register.json" >&2
  exit 1
fi
SECOND_NODE_ID=$(python3 - "$TMP_ROOT/second_register.json" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    data = json.load(handle)
print(data["id"])
PY
)

echo "$SECOND_NODE_ID" > "$TMP_ROOT/second_node_id"

echo "[INFO] Second node registered with id $SECOND_NODE_ID"

# A2 上报健康信息，保持 online
status_payload='{"timestamp":"2025-09-24T00:00:00Z","health":{"log-fluentbit":{"status":"healthy"}}}'
status=$(curl -sS -o "$TMP_ROOT/second_status.json" -w '%{http_code}' -H 'Content-Type: application/json' -X PUT "$API_BASE/nodes/$SECOND_NODE_ID/status" -d "$status_payload")
if [[ "$status" != "200" ]]; then
  echo "[ERROR] Second node status update failed: $status" >&2
  cat "$TMP_ROOT/second_status.json" >&2
  exit 1
fi

# 等待调度器把第二节点标记为 online
second_online=false
for _ in {1..10}; do
  sleep 1
  curl -sS "$API_BASE/nodes/$SECOND_NODE_ID" -o "$TMP_ROOT/second_detail.json" || continue
  if python3 - "$TMP_ROOT/second_detail.json" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)
if node["status"] != "online":
    raise SystemExit(1)
PY
  then
    second_online=true
    break
  fi
done

if [[ "$second_online" != true ]]; then
  echo "[ERROR] Second node did not become online" >&2
  exit 1
fi

# 再次获取统计信息
stats_file="$TMP_ROOT/multi_stats.json"
curl -sS "$API_BASE/nodes/statistics" -o "$stats_file"
python3 - "$stats_file" "$TMP_ROOT/node_id" "$TMP_ROOT/second_node_id" <<'PY'
import json, sys, pathlib
with open(sys.argv[1]) as handle:
    stats = json.load(handle)
first_id = pathlib.Path(sys.argv[2]).read_text().strip()
second_id = pathlib.Path(sys.argv[3]).read_text().strip()
assert stats["total"] == 2, stats
found = {item["status"]: item["count"] for item in stats["status_statistics"]}
assert found.get("offline") == 1, found
assert found.get("online") == 1, found
PY

# 验证 nodes.json 只包含在线节点（应只有第二个 A2）
nodes_json_path="$PRIVATE_ROOT/argus/metric/prometheus/nodes.json"
python3 - "$nodes_json_path" "$SECOND_NODE_ID" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    content = json.load(handle)
expected_id = sys.argv[2]
assert len(content) == 1, content
assert content[0]["node_id"] == expected_id, content
PY

echo "[INFO] Multi-node statistics and nodes.json validated"
