name: Build TWA APK

on:
  push:
    tags: ['v*']
  workflow_dispatch:
    inputs:
      app_url:
        description: 'App URL override (default: https://peds.danvics.com)'
        required: false

env:
  APP_URL: ${{ github.event.inputs.app_url || secrets.APP_URL || 'https://peds.danvics.com' }}

jobs:
  build-apk:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Setup Android SDK
        uses: android-actions/setup-android@v3

      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v4

      - name: Generate Gradle wrapper
        working-directory: android
        run: |
          gradle wrapper --gradle-version=8.5

      - name: Build APK
        working-directory: android
        run: |
          TWA_HOST=$(echo "${{ env.APP_URL }}" | sed 's|https://||;s|http://||;s|/.*||')
          ./gradlew assembleRelease -PTWA_HOST="${TWA_HOST}"

      - name: Sign APK
        if: success() && env.HAS_SIGNING_KEY == 'true'
        env:
          HAS_SIGNING_KEY: ${{ secrets.ANDROID_SIGNING_KEY != '' }}
        run: |
          # Decode signing key
          echo "${{ secrets.ANDROID_SIGNING_KEY }}" | base64 -d > /tmp/release.jks

          # Find the latest build-tools version
          BUILD_TOOLS=$(ls -d $ANDROID_HOME/build-tools/*/ | sort -V | tail -1)
          echo "Using build-tools: $BUILD_TOOLS"

          UNSIGNED=$(find android/app/build/outputs/apk/release -name "*.apk" | head -1)
          echo "Signing: $UNSIGNED"

          # Zipalign
          ${BUILD_TOOLS}zipalign -v -p 4 "$UNSIGNED" /tmp/aligned.apk

          # Sign with apksigner
          ${BUILD_TOOLS}apksigner sign \
            --ks /tmp/release.jks \
            --ks-key-alias "${{ secrets.ANDROID_KEY_ALIAS }}" \
            --ks-pass "pass:${{ secrets.ANDROID_KEYSTORE_PASSWORD }}" \
            --key-pass "pass:${{ secrets.ANDROID_KEY_PASSWORD }}" \
            --out android/app/build/outputs/apk/release/PedScribe-v9-signed.apk \
            /tmp/aligned.apk

          # Verify
          ${BUILD_TOOLS}apksigner verify --print-certs android/app/build/outputs/apk/release/PedScribe-v9-signed.apk

          # Cleanup
          rm -f /tmp/release.jks /tmp/aligned.apk

      - name: Upload APK to Release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v2
        with:
          files: android/app/build/outputs/apk/release/*.apk
          generate_release_notes: true

      - name: Upload artifact
        if: success()
        uses: actions/upload-artifact@v4
        with:
          name: pediatric-scribe-apk
          path: android/app/build/outputs/apk/release/*.apk
          retention-days: 30

      - name: Summary
        run: |
          echo "### TWA APK Build" >> $GITHUB_STEP_SUMMARY
          echo "Built for: ${{ env.APP_URL }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Install options:**" >> $GITHUB_STEP_SUMMARY
          echo "- Download from GitHub Releases" >> $GITHUB_STEP_SUMMARY
          echo "- Obtainium: add repo \`https://github.com/ifedan-ed/pediatric-ai-scribe-v3\`" >> $GITHUB_STEP_SUMMARY
