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

node_id="$(cat "$TMP_ROOT/node_id")"

payload=$(python3 - <<'PY'
import json
from datetime import datetime, timezone
body = {
    "timestamp": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
    "health": {
        "log-fluentbit": {"status": "healthy", "timestamp": "2023-10-05T12:05:00Z"},
        "metric-node-exporter": {"status": "healthy", "timestamp": "2023-10-05T12:05:00Z"}
    }
}
print(json.dumps(body))
PY
)

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

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

echo "$body" > "$TMP_ROOT/last_response.json"

sleep 3

detail_file="$TMP_ROOT/status_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"] == "online", f"Expected online, got {node['status']}"
assert "log-fluentbit" in node["health"], node["health"].keys()
PY

echo "[INFO] Status report successful and node is online"

# 等待超过 offline 阈值，验证会自动转为 offline
sleep 7

offline_detail_file="$TMP_ROOT/status_offline.json"
curl -sS "$API_BASE/nodes/$node_id" -o "$offline_detail_file"
python3 - "$offline_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

echo "[INFO] Node transitioned to offline as expected"

# 再次上报健康，触发状态回到 online
payload=$(python3 - <<'PY'
import json
from datetime import datetime, timezone
body = {
    "timestamp": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
    "health": {
        "log-fluentbit": {"status": "healthy", "timestamp": "2023-10-05T12:05:00Z"},
        "metric-node-exporter": {"status": "healthy", "timestamp": "2023-10-05T12:05:00Z"}
    }
}
print(json.dumps(body))
PY
)

curl -sS -o "$TMP_ROOT/second_status_response.json" -w '%{http_code}' -H 'Content-Type: application/json' -X PUT "$API_BASE/nodes/$node_id/status" -d "$payload" > "$TMP_ROOT/second_status_code"
if [[ $(cat "$TMP_ROOT/second_status_code") != "200" ]]; then
  echo "[ERROR] Second status update failed" >&2
  cat "$TMP_ROOT/second_status_response.json" >&2
  exit 1
fi

sleep 3

final_detail_file="$TMP_ROOT/status_back_online.json"
curl -sS "$API_BASE/nodes/$node_id" -o "$final_detail_file"
python3 - "$final_detail_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)
assert node["status"] == "online", f"Expected online after second report, got {node['status']}"
PY

echo "[INFO] Node transitioned back to online after new status report"
