#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/repo/scripts" "$TMP/repo/k8s/regional" "$TMP/bin"
cp "$ROOT/scripts/render-regional-k8s.sh" "$TMP/repo/scripts/"
cat > "$TMP/bin/envsubst" <<'PY'
#!/usr/bin/env python3
import os,re,sys
s=sys.stdin.read()
s=re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}',lambda m:os.environ.get(m.group(1),m.group(0)),s)
sys.stdout.write(s)
PY
chmod +x "$TMP/bin/envsubst"
cat > "$TMP/repo/k8s/regional/deployment-region.yaml" <<'EOF2'
id=${REGION_ID};replicas=${REGION_REPLICAS};url=${XAI_UPSTREAM_URL};secret=${XAI_SECRET_NAME}
EOF2
cat > "$TMP/repo/k8s/regional/hpa-region.yaml" <<'EOF2'
hpa=${REGION_ID}
EOF2
cat > "$TMP/repo/k8s/regional/service.yaml" <<'EOF2'
service=${APP_NAME}
EOF2
cat > "$TMP/repo/k8s/regional/pdb.yaml" <<'EOF2'
pdb=${APP_NAME}
EOF2
cat > "$TMP/regions.env" <<'EOF2'
APP_NAME=tia
XAI_TARGETS="ORD IAD GRU"
ORD_REGION_ID=ord
ORD_REGION_REPLICAS=1
ORD_XAI_UPSTREAM_URL=wss://ord
ORD_XAI_SECRET_NAME=secret-ord
IAD_REGION_ID=iad
IAD_REGION_REPLICAS=2
IAD_XAI_UPSTREAM_URL=wss://iad
IAD_XAI_SECRET_NAME=secret-iad
GRU_REGION_ID=gru
GRU_REGION_REPLICAS=3
GRU_XAI_UPSTREAM_URL=wss://gru
GRU_XAI_SECRET_NAME=secret-gru
EOF2
PATH="$TMP/bin:$PATH" "$TMP/repo/scripts/render-regional-k8s.sh" "$TMP/regions.env" "$TMP/out"
test -f "$TMP/out/deployment-ord.yaml"
test -f "$TMP/out/deployment-iad.yaml"
test -f "$TMP/out/deployment-gru.yaml"
grep -q 'replicas=3' "$TMP/out/deployment-gru.yaml"
echo 'test_render_regional_multi_target: PASS'
