#!/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"
PRIVATE_ROOT="$TEST_ROOT/private"
API_BASE="http://localhost:31300/api/v1/master"
NODE_ID="$(cat "$TMP_ROOT/node_id")"

payload='{"config":{"log_level":"debug"},"label":["gpu","exp001"]}'

response=$(curl -sS -w '\n%{http_code}' -H 'Content-Type: application/json' -X PUT "$API_BASE/nodes/$NODE_ID/config" -d "$payload")
body="$(echo "$response" | head -n -1)"
status="$(echo "$response" | tail -n1)"

if [[ "$status" != "200" ]]; then
  echo "[ERROR] Config update failed: $status" >&2
  echo "$body" >&2
  exit 1
fi

sleep 2

nodes_json_path="$PRIVATE_ROOT/argus/metric/prometheus/nodes.json"
if [[ ! -f "$nodes_json_path" ]]; then
  echo "[ERROR] nodes.json not generated at $nodes_json_path" >&2
  exit 1
fi

# 确保节点处于 online 状态，避免因等待导致 nodes.json 为空
curl -sS "$API_BASE/nodes/$NODE_ID" -o "$TMP_ROOT/config_detail.json"
if ! python3 - "$TMP_ROOT/config_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
  payload='{"timestamp":"2025-09-24T00:00:00Z","health":{"log-fluentbit":{"status":"healthy"}}}'
  curl -sS -o "$TMP_ROOT/config_second_report.json" -w '%{http_code}' -H 'Content-Type: application/json' -X PUT "$API_BASE/nodes/$NODE_ID/status" -d "$payload" > "$TMP_ROOT/config_second_code"
  sleep 2
fi

python3 - "$nodes_json_path" <<'PY'
import json, sys
from pathlib import Path
path = Path(sys.argv[1])
content = json.loads(path.read_text())
assert isinstance(content, list) and len(content) == 1
entry = content[0]
assert entry["labels"] == ["gpu", "exp001"], entry
PY

echo "[INFO] Config updated and nodes.json verified"
