#!/usr/bin/env bash
# Pushes all flows to Kestra via API. Run after `docker compose up -d`.
set -e

KESTRA_URL="${KESTRA_URL:-http://localhost:8080}"
FLOWS_DIR="$(cd "$(dirname "$0")/../flows" && pwd)"

echo "Waiting for Kestra to be ready..."
until curl -sf "$KESTRA_URL/api/v1/flows/distinct-namespaces" > /dev/null; do
  sleep 2
done

for flow in "$FLOWS_DIR"/*.yml; do
  name=$(basename "$flow")
  result=$(curl -s -o /tmp/kestra_resp.json -w "%{http_code}" \
    -X POST "$KESTRA_URL/api/v1/flows" \
    -H "Content-Type: application/x-yaml" \
    --data-binary "@$flow")
  if [[ "$result" == "200" || "$result" == "409" ]]; then
    # 409 = already exists, try PUT to update
    if [[ "$result" == "409" ]]; then
      ns=$(python3 -c "import sys,json; d=json.load(open('/tmp/kestra_resp.json')); print(d.get('message',''))" 2>/dev/null || echo "")
      id=$(grep '^id:' "$flow" | head -1 | awk '{print $2}')
      namespace=$(grep '^namespace:' "$flow" | head -1 | awk '{print $2}')
      curl -s -X PUT "$KESTRA_URL/api/v1/flows/$namespace/$id" \
        -H "Content-Type: application/x-yaml" \
        --data-binary "@$flow" > /dev/null
      echo "  updated: $name"
    else
      echo "  loaded:  $name"
    fi
  else
    echo "  ERROR ($result): $name"
    cat /tmp/kestra_resp.json
  fi
done

echo ""
echo "Namespaces:"
curl -s "$KESTRA_URL/api/v1/flows/distinct-namespaces" | python3 -m json.tool
