name: Release

on:
  workflow_dispatch:
    inputs:
      tag:
        description: 'Release tag (example: v0.1.0)'
        required: true
        type: string

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ inputs.tag }}
          fetch-depth: 0
      
      - name: Set up JDK 21
        uses: actions/setup-java@v5
        with:
          java-version: '21'
          distribution: 'temurin'
          
      - name: Grant execute permission for gradlew
        run: chmod +x gradlew

      - name: Verify tag matches VERSION
        run: |
          expected="v$(cat VERSION)"
          if [ "$expected" != "${{ inputs.tag }}" ]; then
            echo "Tag ${{ inputs.tag }} does not match VERSION ($expected)"
            exit 1
          fi

      - name: Decode signing keystore
        run: |
          echo "${{ secrets.ANDROID_SIGNING_KEYSTORE_B64 }}" | tr -d '[:space:]' | base64 -d > "$RUNNER_TEMP/release.keystore"
        
      - name: Build signed release artifacts
        env:
          ANDROID_SIGNING_STORE_FILE: ${{ runner.temp }}/release.keystore
          ANDROID_SIGNING_STORE_PASSWORD: ${{ secrets.ANDROID_SIGNING_STORE_PASSWORD }}
          ANDROID_SIGNING_KEY_ALIAS: ${{ secrets.ANDROID_SIGNING_KEY_ALIAS }}
          ANDROID_SIGNING_KEY_PASSWORD: ${{ secrets.ANDROID_SIGNING_KEY_PASSWORD }}
        run: ./gradlew assembleRelease --stacktrace
        
      - name: Rename artifacts
        run: |
          mv app/build/outputs/apk/release/app-release.apk prism.apk

      - name: Upload release artifacts
        uses: actions/upload-artifact@v6
        with:
          name: prism-release-artifacts
          path: |
            prism.apk

      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ inputs.tag }}
          name: Prism ${{ inputs.tag }}
          generate_release_notes: true
          files: |
            prism.apk
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
