name: Release to Google Play
on:
  workflow_dispatch:
    inputs:
      inAppUpdatePriority:
        description: 'In app update priority (0-5)'
        type: number
        default: 0
        required: false

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}

jobs:
  publish-google-play-release:
    runs-on: macos-26
    steps:
    - name: Setup build environment
      uses: msfjarvis/compose-lobsters/.github/reusable-workflows/setup-gradle@92aae743ab8e1c98741128f1bfda3715750f5cf6 # main
      with:
        token: ${{ secrets.POST_RELEASE_GH_TOKEN }}
        fetch-depth: 0
        cache-read-only: ${{ github.ref != 'refs/heads/main' }}
        persist-credentials: true

    - name: Set up Git author
      shell: bash
      run: |
        git config user.name "GitHub Actions"
        git config user.email noreply@github.com

    - name: Decrypt secrets
      run: |
        ./scripts/setup-age.sh
        ./scripts/signing-setup.sh "$AGE_SECRET_KEY"
      env:
        AGE_SECRET_KEY: ${{ secrets.AGE_SECRET_KEY }}

    - name: Get current version
      shell: bash
      run: |
        ./gradlew -q --no-configuration-cache clearPreRelease
        VERSION="$(grep 'versioning-plugin.versionName' android/version.properties | cut -d = -f 2)"
        VERSION_CODE="$(grep 'versioning-plugin.versionCode' android/version.properties | cut -d = -f 2)"
        echo VERSION="${VERSION}" >> $GITHUB_ENV
        echo VERSION_CODE="${VERSION_CODE}" >> $GITHUB_ENV

    - name: Update changelog
      uses: msfjarvis/keep-a-changelog-new-release@e60399f488b25149c0963a4e22fff928a9277ce7 # v2.2.0
      with:
        tag: v${{ env.VERSION }}
        version: ${{ env.VERSION }}

    - name: Get changelog entry
      id: changelog_reader
      uses: mindsers/changelog-reader-action@1faaf50aa09d5793d9a100819973df801febfb31 # v2.4.0
      with:
        version: ${{ env.VERSION }}
        path: ./CHANGELOG.md

    - name: Write changelog to fastlane metadata
      shell: bash
      env:
        CHANGELOG: ${{ steps.changelog_reader.outputs.changes }}
      run: |
        mkdir -p fastlane/metadata/android/en-US/changelogs
        printf '%s\n' "${CHANGELOG}" > fastlane/metadata/android/en-US/changelogs/${VERSION_CODE}.txt

    - name: Commit changes
      shell: bash
      run: |
        git add .
        git commit -m 'feat(release): bump version'

    - name: Calculate VCS info for Sentry
      shell: bash
      run: |
        # Get HEAD commit SHA
        HEAD_SHA=$(git rev-parse HEAD)
        echo "SENTRY_VCS_HEAD_SHA=${HEAD_SHA}" >> $GITHUB_ENV
        
        # Get parent info (format: commit parent1 [parent2...])
        PARENTS=$(git rev-list --parents -n 1 HEAD)
        PARENT_COUNT=$(echo "$PARENTS" | wc -w)
        
        if [ "$PARENT_COUNT" -ge 3 ]; then
          # Merge commit (commit + 2+ parents): use first parent
          BASE_SHA=$(echo "$PARENTS" | awk '{print $2}')
        else
          # Normal commit: use last release
          LAST_TAG=$(gh release list --limit 1 --json tagName -q '.[0].tagName' || echo "")
          if [ -n "$LAST_TAG" ]; then
            BASE_SHA=$(git rev-parse "${LAST_TAG}^{commit}")
          else
            BASE_SHA="${HEAD_SHA}"
          fi
        fi
        echo "SENTRY_VCS_BASE_SHA=${BASE_SHA}" >> $GITHUB_ENV
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

    - name: Build release assets
      shell: bash
      env:
        SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
        SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
        SENTRY_VCS_HEAD_SHA: ${{ env.SENTRY_VCS_HEAD_SHA }}
        SENTRY_VCS_BASE_SHA: ${{ env.SENTRY_VCS_BASE_SHA }}
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        ./gradlew --no-configuration-cache assembleRelease uploadSentryProguardMappingsRelease collectReleaseApks collectReleaseBundle -PenableSentry

    - name: Clean secrets
      run: scripts/signing-cleanup.sh

    - name: Write release notes file
      shell: bash
      env:
        CHANGELOG: ${{ steps.changelog_reader.outputs.changes }}
      run: |
        mkdir -p distribution/whatsnew
        printf '%s' "${CHANGELOG}" >> distribution/whatsnew/whatsnew-en-GB

    - name: Publish bundle to Google Play
      uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1.1.5
      with:
        mappingFile: android/bundle/mapping.txt
        packageName: dev.msfjarvis.claw.android
        releaseFiles: android/bundle/*.aab
        serviceAccountJsonPlainText: ${{ secrets.SERVICE_ACCOUNT_JSON }}
        status: completed
        track: production
        whatsNewDirectory: distribution/whatsnew
        inAppUpdatePriority: ${{ inputs.inAppUpdatePriority }}

    - name: Post-release work
      shell: bash
      env:
        GITHUB_TOKEN: ${{ secrets.POST_RELEASE_GH_TOKEN }}
      run: |
        # Tag the current version
        git tag "v${VERSION}" -F distribution/whatsnew/whatsnew-en-GB

        # Push the tag to GitHub
        git push origin "v${VERSION}"

        # Create GitHub release notes with footer
        RELEASE_NOTES=$(mktemp)
        {
          cat distribution/whatsnew/whatsnew-en-GB
          echo ""
          echo "---"
          echo ""
          echo '<a href="https://play.google.com/store/apps/details?id=dev.msfjarvis.claw.android">'
          echo '  <img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png"'
          echo '       alt="Get it on Google Play"'
          echo '       height="80" />'
          echo '</a>'
          echo ""
          echo '<a href="https://android.izzysoft.de/repo/apk/dev.msfjarvis.claw.android">'
          echo '  <img src="./.github/izzy-badge.webp"'
          echo '       alt="Get it on IzzyOnDroid"'
          echo '       height="65" />'
          echo '</a>'
        } > "$RELEASE_NOTES"

        # Create a GitHub release
        gh release create "v${VERSION}" --notes-file "$RELEASE_NOTES" --title "v${VERSION}" ./android/apk/*.apk ./android/bundle/*.aab

        # Clean up temp file
        rm "$RELEASE_NOTES"

        # Start the next development iteration
        ./gradlew -q --no-configuration-cache bumpSnapshot
        git commit -am 'feat(release): start next development iteration'
        git push -u origin
