#!/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:32300/api/v1/master"
AGENT_HOSTNAME="dev-e2euser-e2einst-pod-0"
NODE_FILE="$TEST_ROOT/private/argus/agent/$AGENT_HOSTNAME/node.json"

mkdir -p "$TMP_ROOT"

node_id=""
for _ in {1..30}; do
  sleep 2
  response=$(curl -sS "$API_BASE/nodes" || true)
  if [[ -z "$response" ]]; then
    continue
  fi
  list_file="$TMP_ROOT/nodes_list.json"
  echo "$response" > "$list_file"
  node_id=$(python3 - "$list_file" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    nodes = json.load(handle)
print(nodes[0]["id"] if nodes else "")
PY
)
  if [[ -n "$node_id" ]]; then
    break
  fi
 done

if [[ -z "$node_id" ]]; then
  echo "[ERROR] Agent did not register within timeout" >&2
  exit 1
fi

echo "$node_id" > "$TMP_ROOT/node_id"

if [[ ! -f "$NODE_FILE" ]]; then
  echo "[ERROR] node.json not created at $NODE_FILE" >&2
  exit 1
fi

python3 - "$NODE_FILE" <<'PY'
import json, sys
with open(sys.argv[1]) as handle:
    node = json.load(handle)
assert "id" in node and node["id"], "node.json missing id"
PY

detail_file="$TMP_ROOT/initial_detail.json"
curl -sS "$API_BASE/nodes/$node_id" -o "$detail_file"
python3 - "$detail_file" "$TMP_ROOT/initial_ip" <<'PY'
import json, sys, pathlib
with open(sys.argv[1]) as handle:
    node = json.load(handle)
ip = node["meta_data"].get("ip")
if not ip:
    raise SystemExit("meta_data.ip missing")
pathlib.Path(sys.argv[2]).write_text(ip)
PY

echo "[INFO] Agent registered with node id $node_id"
