#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

COMPOSE_FILE="${ROOT_DIR}/docker-compose.yaml"

# Container names (refactor)
HEAD_CONTAINER="${HEAD_CONTAINER:-argus-ray-head}"
WORKER0_CONTAINER="${WORKER0_CONTAINER:-argus-ray-worker-0}"
WORKER1_CONTAINER="${WORKER1_CONTAINER:-argus-ray-worker-1}"

SHARED_ROOT="${SHARED_ROOT:-/private}"
RAY_DASHBOARD_ADDR="${RAY_DASHBOARD_ADDR:-http://127.0.0.1:8265}"

dc() {
  docker compose --project-directory "${ROOT_DIR}" -f "${COMPOSE_FILE}" "$@"
}

require_cmd() {
  local cmd="$1"
  command -v "${cmd}" >/dev/null 2>&1 || {
    echo "missing required command: ${cmd}" >&2
    exit 1
  }
}

ensure_container_running() {
  local name="$1"
  if ! docker ps --format '{{.Names}}' | grep -qx "${name}"; then
    echo "container not running: ${name}" >&2
    exit 1
  fi
}

dexec() {
  local name="$1"
  shift
  ensure_container_running "${name}"
  docker exec -i "${name}" "$@"
}

container_ip() {
  local name="$1"
  ensure_container_running "${name}"
  docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${name}"
}

timestamp() {
  date +"%Y%m%d_%H%M%S"
}
