name: Sync Release to GitHub

on:
  workflow_dispatch:

jobs:
  sync-release:
    runs-on: ubuntu-latest
    steps:
      - name: Mirror release to GitHub
        env:
          GH_PAT: ${{ secrets.GH_PAT }}
          GITHUB_REPO: shadowdao/triple-c
          RELEASE_TAG: ${{ gitea.event.release.tag_name }}
          RELEASE_NAME: ${{ gitea.event.release.name }}
          RELEASE_BODY: ${{ gitea.event.release.body }}
          IS_PRERELEASE: ${{ gitea.event.release.prerelease }}
          IS_DRAFT: ${{ gitea.event.release.draft }}
        run: |
          set -e

          echo "==> Creating release $RELEASE_TAG on GitHub..."

          RESPONSE=$(curl -sf -X POST \
            -H "Authorization: Bearer $GH_PAT" \
            -H "Accept: application/vnd.github+json" \
            -H "Content-Type: application/json" \
            https://api.github.com/repos/$GITHUB_REPO/releases \
            -d "{
              \"tag_name\": \"$RELEASE_TAG\",
              \"name\": \"$RELEASE_NAME\",
              \"body\": $(echo "$RELEASE_BODY" | jq -Rs .),
              \"draft\": $IS_DRAFT,
              \"prerelease\": $IS_PRERELEASE
            }")

          UPLOAD_URL=$(echo "$RESPONSE" | jq -r '.upload_url' | sed 's/{?name,label}//')
          echo "Release created. Upload URL: $UPLOAD_URL"

          echo '${{ toJSON(gitea.event.release.assets) }}' | jq -c '.[]' | while read asset; do
            ASSET_NAME=$(echo "$asset" | jq -r '.name')
            ASSET_URL=$(echo "$asset" | jq -r '.browser_download_url')

            echo "==> Downloading asset: $ASSET_NAME"
            curl -sfL -o "/tmp/$ASSET_NAME" "$ASSET_URL"

            echo "==> Uploading $ASSET_NAME to GitHub..."
            ENCODED_NAME=$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$ASSET_NAME")
            curl -sf -X POST \
              -H "Authorization: Bearer $GH_PAT" \
              -H "Accept: application/vnd.github+json" \
              -H "Content-Type: application/octet-stream" \
              --data-binary "@/tmp/$ASSET_NAME" \
              "$UPLOAD_URL?name=$ENCODED_NAME"

            echo "  Uploaded: $ASSET_NAME"
          done

          echo "==> Release sync complete."