name: Build Android App (TWA)

on:
  push:
    branches:
      - main
      - develop
  workflow_dispatch:

jobs:
  build-aab:
    runs-on: ubuntu-latest
    env:
      MANIFEST_URL: https://taprestation.com/manifest.webmanifest
      PACKAGE_ID: com.taprestation.app
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

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

      - name: Install ImageMagick
        run: sudo apt-get update && sudo apt-get install -y imagemagick

      - name: Generate icons
        run: ./scripts/generate-icons.sh

      - name: Install Bubblewrap CLI
        run: npm i -g @bubblewrap/cli

      - name: Initialize Bubblewrap (non-interactive)
        run: | 
          chmod +x twa/init-noninteractive.sh
          twa/init-noninteractive.sh $MANIFEST_URL $PACKAGE_ID

      - name: Build Android project via Bubblewrap
        run: bubblewrap build --manifest $MANIFEST_URL --host https://taprestation.com --packageId $PACKAGE_ID

      - name: Configure signing (write key file)
        env:
          KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
          KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
          KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
        run: |
          mkdir -p android/keystore
          echo "$KEYSTORE_BASE64" | base64 --decode > android/keystore/ta-prestation.keystore
          cat > android/keystore.properties <<EOL
          storeFile=keystore/ta-prestation.keystore
          storePassword=$KEYSTORE_PASSWORD
          keyAlias=$KEY_ALIAS
          keyPassword=$KEY_PASSWORD
          EOL

      - name: Build release AAB
        working-directory: android
        run: ./gradlew bundleRelease -Pandroid.injected.signing.store.file=keystore/ta-prestation.keystore -Pandroid.injected.signing.store.password=${{ secrets.ANDROID_KEYSTORE_PASSWORD }} -Pandroid.injected.signing.key.alias=${{ secrets.ANDROID_KEY_ALIAS }} -Pandroid.injected.signing.key.password=${{ secrets.ANDROID_KEY_PASSWORD }}

      - name: Upload artifact for download
        uses: actions/upload-artifact@v4
        with:
          name: app-aab
          path: android/app/build/outputs/bundle/release/app-release.aab

      - name: (Optional) Publish to Play Store
        if: ${{ secrets.PLAY_STORE_JSON != '' }}
        uses: r0adkll/upload-google-play@v1
        with:
          serviceAccountJson: ${{ secrets.PLAY_STORE_JSON }}
          packageName: $PACKAGE_ID
          releaseFile: android/app/build/outputs/bundle/release/app-release.aab
          track: internal
