#!/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"
NODE_ID="$(cat "$TMP_ROOT/node_id")"

sleep 7

detail_file="$TMP_ROOT/offline_detail.json"
curl -sS "$API_BASE/nodes/$NODE_ID" -o "$detail_file"
python3 - "$detail_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)
assert node["status"] == "offline", f"Expected offline, got {node['status']}"
PY

stats_file="$TMP_ROOT/stats.json"
curl -sS "$API_BASE/nodes/statistics" -o "$stats_file"
python3 - "$stats_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    stats = json.load(handle)
assert stats["total"] == 1
found = {item["status"]: item["count"] for item in stats["status_statistics"]}
assert found.get("offline") == 1
PY

nodes_json_path="$PRIVATE_ROOT/argus/metric/prometheus/nodes.json"
python3 - "$nodes_json_path" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    content = json.load(handle)
assert content == [], content
PY

echo "[INFO] Offline transition and statistics validated"
