name: Sync releases to adamlui/<js|python>-utils

on:
  release:
    types: [published, edited]

jobs:
  sync-release:
    name: Sync release to adamlui/<js|python>-utils
    runs-on: ubuntu-24.04
    permissions:
      contents: read

    steps:
      - name: Generate KSB token
        id: ksb-token
        uses: actions/create-github-app-token@v3.1.1
        with:
          client-id: ${{ secrets.KSB_APP_ID }}
          private-key: ${{ secrets.KSB_PRIVATE_KEY }}
          owner: adamlui

      - name: Sync release to adamlui/<js|python>-utils
        run: |
          RELEASE_TITLE="${{ github.event.release.name }}"
          RELEASE_TAG="${{ github.event.release.tag_name }}"
          echo "Source Title: $RELEASE_TITLE"
          echo "Source Tag: $RELEASE_TAG"

          RUNTIME="${RELEASE_TAG%%-*}"
          TARGET_REPO="adamlui/${RUNTIME/node.js/js}-utils"
          RELEASE_JSON=$(curl -s "https://api.github.com/repos/KudoAI/ai-personas/releases/tags/$RELEASE_TAG")
          RELEASE_NOTES=$(echo "$RELEASE_JSON" | sed -nE 's/.*"body": "(.*)".*/\1/p')

          if [[ "$RELEASE_NOTES" == *"Auto-synced from"* ]] ; then
            echo "Release already auto-synced. Exiting..." ; exit 0 ; fi

          # Convert emoji
          RELEASE_NOTES=$(echo "$RELEASE_NOTES" | \
            sed 's|📃|:page_with_curl:|g; s|🚀|:rocket:|g; s|🧠|:brain:|g; s|💻|:computer:|g')

          TARGET_RELEASE_TITLE=$(echo "$RELEASE_TITLE" | sed -E 's/ \((Python|Node\.js)\)//')
          TARGET_RELEASE_TAG="ai-personas-$(echo "$RELEASE_TAG" | sed -E 's/^[^-]+-v//')"
          echo "Target Title: $TARGET_RELEASE_TITLE"
          echo "Target Tag: $TARGET_RELEASE_TAG"

          # Check release exists in adamlui/python-utils
          RELEASE_CHECK_RESP=$(curl -s \
            "https://api.github.com/repos/$TARGET_REPO/releases/tags/$TARGET_RELEASE_TAG")
          TARGET_RELEASE_ID=$(echo "$RELEASE_CHECK_RESP" | sed -nE 's/.*"id":[[:space:]]*([0-9]+).*/\1/p' | head -1)
          if [ -n "$TARGET_RELEASE_ID" ] ; then
            RELEASE_EXISTS=true
            echo "Release exists (ID: $TARGET_RELEASE_ID)"
          else
            RELEASE_EXISTS=false
            echo "Release does not exist"
          fi

          # Append auto-sync trailer
          RELEASE_NOTES+="\n\n###### _Auto-synced from https://github.com/KudoAI/ai-personas/releases"
          RELEASE_NOTES+=" by [@kudo-sync-bot](https://github.com/kudo-sync-bot)_"

          if [ "$RELEASE_EXISTS" = false ] ; then
            echo "Creating new release..."
            create_release_url="https://api.github.com/repos/$TARGET_REPO/releases"
            create_release_payload=$(
              printf '{"tag_name": "%s","name": "%s","body": "%s"}' \
                "$TARGET_RELEASE_TAG" "$TARGET_RELEASE_TITLE" "$RELEASE_NOTES")
            create_release_resp=$(
              curl -s -S -X POST -H "Authorization: Bearer ${{ steps.ksb-token.outputs.token }}" \
                   -H "Content-Type: application/json" -d "$create_release_payload" "$create_release_url")
            if echo "$create_release_resp" | grep -q '"message"' ; then
              echo "ERROR: Failed to create release: $create_release_resp"
              exit 1
            fi
            upload_url=$(echo "$create_release_resp" | sed -nE 's|.*"upload_url": "(.*)".*|\1|p' | sed 's|{.*}||')
          else
            echo "Updating existing release..."
            update_release_url="https://api.github.com/repos/$TARGET_REPO/releases/$TARGET_RELEASE_ID"
            update_release_payload=$(
              printf '{"name": "%s","body": "%s"}' \
                "$TARGET_RELEASE_TITLE" "$RELEASE_NOTES")
            patch_release_resp=$(
              curl -s -S -X PATCH -H "Authorization: Bearer ${{ steps.ksb-token.outputs.token }}" \
                   -H "Content-Type: application/json" -d "$update_release_payload" "$update_release_url")
            if echo "$patch_release_resp" | grep -q '"message"' ; then
              echo "ERROR: Failed to update release: $patch_release_resp"
              exit 1
            fi
            get_release_resp=$(curl -s -S -H "Authorization: Bearer ${{ steps.ksb-token.outputs.token }}" \
              "https://api.github.com/repos/$TARGET_REPO/releases/tags/$TARGET_RELEASE_TAG")
            upload_url=$(echo "$get_release_resp" | sed -nE 's|.*"upload_url": "(.*)".*|\1|p' | sed 's|{.*}||')
          fi

          echo "Release synced to $TARGET_REPO ($TARGET_RELEASE_TAG)!"
