#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${1:-$ROOT/k8s/regional/regions.env}"
OUT="${2:-$ROOT/k8s/regional/rendered}"
[[ -f "$ENV_FILE" ]] || { echo "Missing $ENV_FILE (copy regions.env.example)" >&2; exit 2; }
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
command -v envsubst >/dev/null || { echo "envsubst is required (gettext package)" >&2; exit 2; }

XAI_TARGETS="${XAI_TARGETS:-${XAI_REGIONS:-}}"
[[ -n "${XAI_TARGETS// }" ]] || {
  echo 'XAI_TARGETS is required. Example: XAI_TARGETS="ORD IAD GRU"' >&2
  exit 2
}

rm -rf "$OUT"
mkdir -p "$OUT"

required_target_var() {
  local target="$1" suffix="$2" var value
  var="${target}_${suffix}"
  value="${!var:-}"
  [[ -n "$value" ]] || { echo "Missing required configuration: $var" >&2; exit 2; }
  printf '%s' "$value"
}

render_target() {
  local target="$1"
  [[ "$target" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || {
    echo "Invalid XAI target '$target'. Use letters, numbers and underscores only." >&2
    exit 2
  }

  export REGION_ID REGION_REPLICAS XAI_UPSTREAM_URL XAI_SECRET_NAME
  REGION_ID="$(required_target_var "$target" REGION_ID)"
  REGION_REPLICAS="$(required_target_var "$target" REGION_REPLICAS)"
  XAI_UPSTREAM_URL="$(required_target_var "$target" XAI_UPSTREAM_URL)"
  XAI_SECRET_NAME="$(required_target_var "$target" XAI_SECRET_NAME)"

  [[ "$REGION_ID" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || {
    echo "Invalid ${target}_REGION_ID='$REGION_ID'. Use a lowercase Kubernetes label." >&2
    exit 2
  }
  [[ ! -e "$OUT/deployment-${REGION_ID}.yaml" ]] || {
    echo "Duplicate REGION_ID '$REGION_ID'. Each target must have a unique REGION_ID." >&2
    echo "For multiple pools in one OCI region use ids such as ord-primary and ord-secondary." >&2
    exit 2
  }

  envsubst < "$ROOT/k8s/regional/deployment-region.yaml" > "$OUT/deployment-${REGION_ID}.yaml"
  envsubst < "$ROOT/k8s/regional/hpa-region.yaml" > "$OUT/hpa-${REGION_ID}.yaml"
  echo "Rendered target=$target region_id=$REGION_ID"
}

for target in $XAI_TARGETS; do
  render_target "$target"
done

envsubst < "$ROOT/k8s/regional/service.yaml" > "$OUT/service.yaml"
envsubst < "$ROOT/k8s/regional/pdb.yaml" > "$OUT/pdb.yaml"
echo "Rendered manifests in $OUT"
