name: Android Build

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  android-build:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      with:
        submodules: recursive
    
    - name: Set up JDK 17
      uses: actions/setup-java@v4
      with:
        java-version: '17'
        distribution: 'temurin'
    
    - name: Setup Android SDK
      uses: android-actions/setup-android@v3
    
    - name: Install NDK
      run: |
        sdkmanager "ndk;25.1.8937393"
        echo "ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/25.1.8937393" >> $GITHUB_ENV
    
    - name: Setup Gradle
      uses: gradle/gradle-build-action@v2
      with:
        gradle-version: 8.2
    
    - name: Cache Gradle packages
      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: Generate Gradle Wrapper
      run: |
        cd android
        gradle wrapper --gradle-version 8.2
    
    - name: Make gradlew executable
      run: chmod +x android/gradlew
      
    - name: Copy assets (if needed)
      run: |
        cd android
        if [ -f "copy_assets.bat" ]; then
          echo "Asset copy scripts found"
        fi
      
    - name: Build Debug APK
      run: |
        cd android
        ./gradlew assembleDebug --stacktrace
    
    - name: Build Release APK
      run: |
        cd android
        ./gradlew assembleRelease --stacktrace
    
    - name: Upload Debug APK
      uses: actions/upload-artifact@v4
      with:
        name: torch-converter-debug
        path: android/app/build/outputs/apk/debug/app-debug.apk
        retention-days: 30
    
    - name: Upload Release APK
      uses: actions/upload-artifact@v4
      with:
        name: torch-converter-release
        path: android/app/build/outputs/apk/release/app-release.apk
        retention-days: 30
    
    - name: APK Info
      run: |
        echo "Debug APK size: $(du -h android/app/build/outputs/apk/debug/app-debug.apk | cut -f1)"
        echo "Release APK size: $(du -h android/app/build/outputs/apk/release/app-release.apk | cut -f1)"