# ────────────────────────────────────────────────────────────
# Native Android CI/CD → DeployHub
#
# Copy this file to your Android project:
#   .github/workflows/deployhub.yml
#
# Required GitHub Secrets:
#   DEPLOYHUB_API_KEY   – API key from DeployHub
#   DEPLOYHUB_URL       – e.g. https://deployhub-back.workzy.co
#   KEYSTORE_BASE64     – base64-encoded .jks keystore
#   KEYSTORE_PASSWORD   – keystore password
#   KEY_ALIAS           – key alias
#   KEY_PASSWORD        – key password
#
# Optional Secrets:
#   DEPLOYHUB_FRONTEND_URL – e.g. https://deployhub.workzy.co
# ────────────────────────────────────────────────────────────
name: Android → DeployHub

on:
  push:
    branches: [development]
  workflow_dispatch:
    inputs:
      release_notes:
        description: 'Release notes for this build'
        required: false
        type: string

concurrency:
  group: android-deploy-${{ github.ref }}
  cancel-in-progress: true

env:
  JAVA_VERSION: '17'

jobs:
  build-and-deploy:
    name: Build APK & Upload to DeployHub
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: ${{ env.JAVA_VERSION }}

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

      - name: Setup Android signing
        env:
          KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
        run: |
          echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 --decode > app/keystore.jks
          export KEYSTORE_ABS="$(cd app && pwd)/keystore.jks"
          echo "Keystore at: $KEYSTORE_ABS"

          mkdir -p ~/.gradle/init.d
          python3 <<'PYEOF'
          import os, textwrap

          ks   = os.environ["KEYSTORE_ABS"]
          ksp  = os.environ["KEYSTORE_PASSWORD"]
          ka   = os.environ["KEY_ALIAS"]
          kp   = os.environ["KEY_PASSWORD"]

          groovy_println = 'println "CI signing config applied to ' + "$" + '{project.path}"'

          script = textwrap.dedent(f'''\
          allprojects {{
            afterEvaluate {{ project ->
              if (project.plugins.hasPlugin("com.android.application")) {{
                project.android {{
                  signingConfigs {{
                    ciRelease {{
                      storeFile     file("{ks}")
                      storePassword "{ksp}"
                      keyAlias      "{ka}"
                      keyPassword   "{kp}"
                    }}
                  }}
                  buildTypes {{
                    release {{
                      signingConfig signingConfigs.ciRelease
                    }}
                  }}
                }}
                {groovy_println}
              }}
            }}
          }}
          ''')

          out = os.path.expanduser("~/.gradle/init.d/ci-signing.gradle")
          with open(out, "w") as f:
              f.write(script)
          print(f"Gradle init script created at {out}")
          print(script)
          PYEOF

      - name: Build Release APK
        run: ./gradlew assembleRelease --no-daemon

      - name: Upload to DeployHub
        env:
          DEPLOYHUB_API_KEY: ${{ secrets.DEPLOYHUB_API_KEY }}
          DEPLOYHUB_URL: ${{ secrets.DEPLOYHUB_URL }}
          DEPLOYHUB_FRONTEND_URL: ${{ secrets.DEPLOYHUB_FRONTEND_URL }}
        run: |
          APK_PATH=$(find app/build/outputs/apk/release -name "*.apk" -type f | head -1)
          if [ -z "$APK_PATH" ]; then
            echo "::error::No release APK found"
            exit 1
          fi
          echo "Uploading $(basename "$APK_PATH")..."

          NOTES="${{ inputs.release_notes || format('Build from {0} @ {1}', github.ref_name, github.sha) }}"

          HTTP_CODE=$(curl --silent --show-error --location --max-time 600 \
            --output /tmp/upload_response.json \
            --write-out "%{http_code}" \
            -H "X-API-Key: ${DEPLOYHUB_API_KEY}" \
            -F "file=@${APK_PATH}" \
            -F "releaseNotes=${NOTES}" \
            "${DEPLOYHUB_URL}/api/builds/ci-upload")

          RESPONSE=$(cat /tmp/upload_response.json)
          echo "HTTP Status: $HTTP_CODE"
          echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"

          if [ "$HTTP_CODE" -lt 200 ] || [ "$HTTP_CODE" -ge 300 ]; then
            echo "::error::Upload failed with HTTP $HTTP_CODE"
            exit 1
          fi

          SHORT_CODE=$(echo "$RESPONSE" | jq -r '.shortCode // empty')
          VERSION=$(echo "$RESPONSE" | jq -r '.version // empty')
          APP_NAME=$(echo "$RESPONSE" | jq -r '.app.appName // empty')
          if [ -n "$SHORT_CODE" ]; then
            echo "### DeployHub Upload" >> $GITHUB_STEP_SUMMARY
            echo "- **App:** ${APP_NAME}" >> $GITHUB_STEP_SUMMARY
            echo "- **Version:** ${VERSION}" >> $GITHUB_STEP_SUMMARY
            echo "- **Short Code:** ${SHORT_CODE}" >> $GITHUB_STEP_SUMMARY
            if [ -n "${DEPLOYHUB_FRONTEND_URL:-}" ]; then
              echo "- **Install:** [${DEPLOYHUB_FRONTEND_URL}/install/${SHORT_CODE}](${DEPLOYHUB_FRONTEND_URL}/install/${SHORT_CODE})" >> $GITHUB_STEP_SUMMARY
            fi
          fi
