name: Update sustainability min-instances

on:
  workflow_dispatch:
    inputs:
      min_instances:
        description: "Min instances to set (e.g. 3)"
        required: true
        default: "3"

env:
  PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
  REGION: us-central1

jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v2

      - name: Update all sustainability services
        run: |
          set -euo pipefail
          MIN="${{ inputs.min_instances }}"

          SERVICES=(
            model-building-game-en-sustainability
            model-building-game-ca-sustainability
            model-building-game-es-sustainability
            model-building-game-en-final-sustainability
            model-building-game-es-final-sustainability
            model-building-game-ca-final-sustainability
            bias-detective-en-sustainability
            bias-detective-ca-sustainability
            bias-detective-es-sustainability
            fairness-fixer-en-sustainability
            fairness-fixer-ca-sustainability
            fairness-fixer-es-sustainability
            sustainability-upgrade-en
            sustainability-upgrade-ca
            sustainability-upgrade-es
            moral-compass-en-sustainability
            moral-compass-es-sustainability
            moral-compass-ca-sustainability
          )

          FAILED=()
          for SVC in "${SERVICES[@]}"; do
            echo "--- Updating ${SVC} to min-instances=${MIN} ---"
            if gcloud run services update "${SVC}" \
              --min-instances="${MIN}" \
              --region="${REGION}" \
              --project="${PROJECT_ID}" 2>&1; then
              echo "✅ ${SVC} updated"
            else
              echo "❌ ${SVC} failed"
              FAILED+=("${SVC}")
            fi
          done

          echo ""
          echo "=== Summary ==="
          echo "Updated $((${#SERVICES[@]} - ${#FAILED[@]})) / ${#SERVICES[@]} services to min-instances=${MIN}"
          if [ ${#FAILED[@]} -gt 0 ]; then
            echo "Failed: ${FAILED[*]}"
            exit 1
          fi
