#!/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"
ENV_AGENT_HOSTNAME="host_abc"
NODE_FILE="$TEST_ROOT/private/argus/agent/$AGENT_HOSTNAME/node.json"
ENV_NODE_FILE="$TEST_ROOT/private/argus/agent/$ENV_AGENT_HOSTNAME/node.json"

mkdir -p "$TMP_ROOT"

primary_node_id=""
env_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"
  readarray -t node_ids < <(python3 - "$list_file" "$AGENT_HOSTNAME" "$ENV_AGENT_HOSTNAME" <<'PY'
import json, sys

with open(sys.argv[1]) as handle:
    nodes = json.load(handle)

target_primary = sys.argv[2]
target_env = sys.argv[3]

primary_id = ""
env_id = ""

for node in nodes:
    if node.get("name") == target_primary:
        primary_id = node.get("id", "")
    if node.get("name") == target_env:
        env_id = node.get("id", "")

print(primary_id)
print(env_id)
PY
  )

  primary_node_id="${node_ids[0]}"
  env_node_id="${node_ids[1]}"

  if [[ -n "$primary_node_id" && -n "$env_node_id" ]]; then
    break
  fi
 done

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

if [[ -z "$env_node_id" ]]; then
  echo "[ERROR] Env-variable agent did not register within timeout" >&2
  exit 1
fi

echo "$primary_node_id" > "$TMP_ROOT/node_id"
echo "$env_node_id" > "$TMP_ROOT/node_id_host_abc"

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

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

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

detail_file="$TMP_ROOT/initial_detail.json"
curl -sS "$API_BASE/nodes/$primary_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 $primary_node_id"
echo "[INFO] Env-variable agent registered with node id $env_node_id"
