#!/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"

mkdir -p "$TMP_ROOT"

for _ in {1..30}; do
  if curl -sf "$API_BASE/healthz" >/dev/null; then
    break
  fi
  sleep 1
done

payload=$(cat <<'JSON'
{
  "name": "dev-testuser-testinst-pod-0",
  "type": "agent",
  "meta_data": {
    "hostname": "dev-testuser-testinst-pod-0",
    "ip": "10.0.0.10",
    "env": "dev",
    "user": "testuser",
    "instance": "testinst",
    "cpu_number": 4,
    "memory_in_bytes": 2147483648,
    "gpu_number": 0
  },
  "version": "1.1.0"
}
JSON
)

body_file="$TMP_ROOT/register_body.json"
status=$(curl -sS -o "$body_file" -w '%{http_code}' -H 'Content-Type: application/json' -X POST "$API_BASE/nodes" -d "$payload")
body="$(cat "$body_file")"

if [[ "$status" != "201" ]]; then
  echo "[ERROR] Unexpected status code: $status" >&2
  echo "$body" >&2
  exit 1
fi

node_id=$(python3 - "$body_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    body = json.load(handle)
print(body["id"])
PY
)

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

list_file="$TMP_ROOT/nodes_list.json"
curl -sS "$API_BASE/nodes" -o "$list_file"
python3 - "$list_file" "$node_id" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    data = json.load(handle)
node_id = sys.argv[2]
assert any(item.get("id") == node_id for item in data), "node not in list"
PY

echo "[INFO] Registered node with id $node_id"
