name: Release APK on Tag

on:
  push:
    tags:
      - '*'

jobs:
  build-and-release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'

      - name: Cache Gradle
        uses: actions/cache@v4
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
          restore-keys: |
            ${{ runner.os }}-gradle-

      - name: Build release APK
        run: ./gradlew :app:assembleRelease --no-daemon --stacktrace

      - name: Find APK
        id: find_apk
        run: |
          set -e
          APK=$(ls app/build/outputs/apk/release/*.apk | head -n1 || true)
          if [ -z "$APK" ]; then
            echo "No APK found in app/build/outputs/apk/release"
            exit 1
          fi
          echo "APK_PATH=$APK" >> $GITHUB_ENV
          echo "apk=$APK"

      - name: Upload artifact (for debugging)
        uses: actions/upload-artifact@v4
        with:
          name: app-release-apk
          path: ${{ env.APK_PATH }}

      - name: Create GitHub Release
        id: create_release
        uses: actions/create-release@v1
        with:
          tag_name: ${{ github.ref_name }}
          release_name: Release ${{ github.ref_name }}
          body: Automated release for tag ${{ github.ref_name }}
          draft: false
          prerelease: false

      - name: Upload APK to Release
        uses: actions/upload-release-asset@v1
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: ${{ env.APK_PATH }}
          asset_name: app-release.apk
          asset_content_type: application/vnd.android.package-archive
