name: PR Build Check
on:
  pull_request:
    branches: [ main ]
    paths:
      - 'android/**'
      - '.github/workflows/pr-build-check.yml'
jobs:
  build:
    name: Build & Test APK
    runs-on: ubuntu-latest
    steps:
      - name: Code auschecken
        uses: actions/checkout@v4
      - name: Java einrichten
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'
      - name: Gradle Cache
        uses: actions/cache@v3
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
          restore-keys: |
            ${{ runner.os }}-gradle-
      - name: Version auslesen
        run: |
          VERSION_NAME=$(grep "versionName = " android/app/build.gradle.kts | sed 's/.*versionName = "\(.*\)".*/\1/')
          VERSION_CODE=$(grep "versionCode = " android/app/build.gradle.kts | sed 's/.*versionCode = \([0-9]*\).*/\1/')
          echo "VERSION_NAME=$VERSION_NAME" >> $GITHUB_ENV
          echo "VERSION_CODE=$VERSION_CODE" >> $GITHUB_ENV
          echo "📱 Version: $VERSION_NAME (Code: $VERSION_CODE)"
      
      # 🔍 Code Quality Checks (v1.6.1)
      - name: Run detekt (Code Quality)
        run: |
          cd android
          ./gradlew detekt --no-daemon
        continue-on-error: false
      
      - name: Run ktlint (Code Style)
        run: |
          cd android
          ./gradlew ktlintCheck --no-daemon
        continue-on-error: true  # Parser-Probleme in Legacy-Code
      
      - name: Upload Lint Reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: lint-reports-pr-${{ github.event.pull_request.number }}
          path: |
            android/app/build/reports/detekt/
            android/app/build/reports/ktlint/
            android/app/build/reports/lint-results*.html
          retention-days: 7
      
      - name: Debug Build erstellen (ohne Signing)
        run: |
          cd android
          ./gradlew assembleStandardDebug assembleFdroidDebug --no-daemon --stacktrace
      - name: Unit Tests ausfuehren
        run: |
          cd android
          ./gradlew test --no-daemon --stacktrace
        continue-on-error: true
      - name: Build-Ergebnis pruefen
        run: |
          if [ -f "android/app/build/outputs/apk/standard/debug/app-standard-universal-debug.apk" ]; then
            echo "✅ Standard Debug APK erfolgreich gebaut"
            ls -lh android/app/build/outputs/apk/standard/debug/*.apk
          else
            echo "❌ Standard Debug APK Build fehlgeschlagen"
            exit 1
          fi
          if [ -f "android/app/build/outputs/apk/fdroid/debug/app-fdroid-universal-debug.apk" ]; then
            echo "✅ F-Droid Debug APK erfolgreich gebaut"
            ls -lh android/app/build/outputs/apk/fdroid/debug/*.apk
          else
            echo "❌ F-Droid Debug APK Build fehlgeschlagen"
            exit 1
          fi
      - name: Debug APKs hochladen (Artefakte)
        uses: actions/upload-artifact@v4
        with:
          name: debug-apks-pr-${{ github.event.pull_request.number }}
          path: |
            android/app/build/outputs/apk/standard/debug/*.apk
            android/app/build/outputs/apk/fdroid/debug/*.apk
          retention-days: 30
      - name: Kommentar zu PR hinzufuegen
        uses: actions/github-script@v7
        if: success()
        with:
          script: |
            const fs = require('fs');
            const standardApk = fs.readdirSync('android/app/build/outputs/apk/standard/debug/')
              .filter(f => f.endsWith('.apk'));
            const fdroidApk = fs.readdirSync('android/app/build/outputs/apk/fdroid/debug/')
              .filter(f => f.endsWith('.apk'));
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## ✅ Build erfolgreich!
            
            **Version:** ${{ env.VERSION_NAME }} (Code: ${{ env.VERSION_CODE }})
            
            ### 📦 Debug APKs (Test-Builds)
            Die Debug-APKs wurden erfolgreich gebaut und sind als Artefakte verfuegbar:
            
            **Standard Flavor:**
            ${standardApk.map(f => '- \`' + f + '\`').join('\n')}
            
            **F-Droid Flavor:**
            ${fdroidApk.map(f => '- \`' + f + '\`').join('\n')}
            
            > ⚠️ **Hinweis:** Dies sind unsigned Debug-Builds zum Testen. Production Releases werden nur bei Merge auf \`main\` erstellt.
            
            [📥 Download Artefakte](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})`
            })