name: Build APK

on:
  push:
    tags:
      - 'v*'

jobs:
  build:
    runs-on: ubuntu-latest
    container:
      image: cimg/android:2024.01

    steps:
      - name: Install Node.js
        run: |
          sudo apt-get update
          sudo apt-get install -y curl
          curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
          sudo apt-get install -y nodejs
      - name: Checkout
        uses: actions/checkout@v4

      - name: Generate Gradle Wrapper
        run: gradle wrapper

      - name: Grant execute permission
        run: chmod +x ./gradlew

      - name: Package and upload webapp
        env:
          UPLOAD_WEBAPP_URL: ${{ secrets.UPLOAD_WEBAPP_URL }}
          UPLOAD_WEBAPP_TOKEN: ${{ secrets.UPLOAD_WEBAPP_TOKEN }}
        run: |
          set -e
          # create webapp zip and upload to configured URL (if provided)
          ./gradlew zipWebApp uploadWebApp

      - name: Update version in assets
        run: |
          set -e
          TAG="${{ github.ref_name }}"
          # Jeśli tag jest pusty (np. push nie na tag), użyjemy skróconego SHA
          if [ -z "$TAG" ] || [ "$TAG" = "main" ]; then
            TAG=$(git rev-parse --short HEAD)
          fi
          echo "Setting version to: $TAG"
          # Aktualizacja pliku js/version.js
          echo "const APP_VERSION = '$TAG';" > app/src/main/assets/js/version.js
          echo "document.addEventListener('DOMContentLoaded', () => {
            const el = document.getElementById('app-version') || document.getElementById('commit-sha');
            if (el) el.textContent = '$TAG';
          });" >> app/src/main/assets/js/version.js

      - name: Build APK
        run: ./gradlew assembleRelease

      - name: Locate APK
        id: locate_apk
        run: |
          set -e
          APK_PATH=$(ls app/build/outputs/apk/release/*.apk | head -n1 || true)
          if [ -z "$APK_PATH" ]; then
            echo "No APK found in app/build/outputs/apk/release" >&2
            exit 1
          fi
          echo "APK_PATH=$APK_PATH" >> $GITHUB_ENV
          echo "Found $APK_PATH"

  # Note: uploading artifacts with actions/upload-artifact@v4 is not supported
  # on some self-hosted/enterprise runners (GHES). We skip storing artifacts
  # via that action and instead upload the APK directly to the Gitea release
  # in the steps below.

      - name: Create Gitea release
        id: create_release
        env:
          GITEA_TOKEN: ${{ secrets.GIT_TOKEN }}
          GITEA_SERVER: ${{ secrets.GIT_SERVER }}
        run: |
          set -e
          SERVER_CLEAN=$(echo "$GITEA_SERVER" | sed 's#/$##')
          API_BASE="${SERVER_CLEAN}/api/v1"

          OWNER="${{ github.repository_owner }}"
          REPO_NAME=$(echo "${{ github.repository }}" | cut -d/ -f2)
          TAG="${{ github.ref_name }}"

          echo "Debug Info:"
          echo "- API URL: $API_BASE/repos/$OWNER/$REPO_NAME/releases"
          echo "- OWNER: $OWNER"
          echo "- REPO: $REPO_NAME"
          echo "- TAG: $TAG"

          # Próba utworzenia release z przechwyceniem statusu HTTP
          RESPONSE_FILE=$(mktemp)
          HTTP_STATUS=$(curl -s -o "$RESPONSE_FILE" -w "%{http_code}" \
            -H "Content-Type: application/json" \
            -H "Authorization: token $GITEA_TOKEN" \
            -X POST \
            -d "{
              \"tag_name\": \"$TAG\",
              \"name\": \"$TAG\",
              \"body\": \"Automated release for $TAG\",
              \"draft\": false,
              \"prerelease\": false
            }" \
            "$API_BASE/repos/$OWNER/$REPO_NAME/releases")

          RESPONSE_BODY=$(cat "$RESPONSE_FILE")
          echo "HTTP Status: $HTTP_STATUS"
          echo "Response: $RESPONSE_BODY"

          if [ "$HTTP_STATUS" -eq 409 ]; then
            echo "Release already exists, fetching existing ID..."
            RESPONSE_BODY=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$API_BASE/repos/$OWNER/$REPO_NAME/releases/tags/$TAG")
            RELEASE_ID=$(echo "$RESPONSE_BODY" | sed -n 's/.*"id":\([0-9]*\),.*/\1/p' | head -n1)
          elif [ "$HTTP_STATUS" -eq 201 ]; then
            RELEASE_ID=$(echo "$RESPONSE_BODY" | sed -n 's/.*"id":\([0-9]*\),.*/\1/p' | head -n1)
          else
            echo "Failed to create release. Expected 201 or 409, got $HTTP_STATUS"
            exit 1
          fi

          if [ -z "$RELEASE_ID" ]; then
            echo "Failed to extract RELEASE_ID from response"
            exit 1
          fi

          echo "RELEASE_ID=$RELEASE_ID" >> $GITHUB_ENV
          echo "Successfully processed release ID: $RELEASE_ID"

      - name: Upload APK to Gitea release
        env:
          GITEA_TOKEN: ${{ secrets.GIT_TOKEN }}
          GITEA_SERVER: ${{ secrets.GIT_SERVER }}
        run: |
          set -e
          SERVER_CLEAN=$(echo "$GITEA_SERVER" | sed 's#/$##')
          API_BASE="${SERVER_CLEAN}/api/v1"

          OWNER="${{ github.repository_owner }}"
          REPO_NAME=$(echo "${{ github.repository }}" | cut -d/ -f2)
          TAG="${{ github.ref_name }}"

          if [ -z "$APK_PATH" ]; then
            echo "APK_PATH not set" >&2
            exit 1
          fi
          if [ -z "$RELEASE_ID" ]; then
            echo "RELEASE_ID not set" >&2
            exit 1
          fi

          # Tworzymy ładną nazwę dla pliku
          FRIENDLY_NAME="Matma-${TAG}.apk"
          cp "$APK_PATH" "./$FRIENDLY_NAME"

          UPLOAD_URL="$API_BASE/repos/$OWNER/$REPO_NAME/releases/$RELEASE_ID/assets?name=$FRIENDLY_NAME"
          echo "Uploading $FRIENDLY_NAME to $UPLOAD_URL"

          curl --fail -s -H "Authorization: token $GITEA_TOKEN" \
               -H "Content-Type: application/octet-stream" \
               --data-binary @"./$FRIENDLY_NAME" \
               "$UPLOAD_URL"

          # Dodanie bezpośredniego linku do podsumowania buildu w Gitea
          DOWNLOAD_URL="${SERVER_CLEAN}/${OWNER}/${REPO_NAME}/releases/download/${TAG}/${FRIENDLY_NAME}"
          echo "### ✅ APK gotowy do pobrania!" >> $GITHUB_STEP_SUMMARY
          echo "[Pobierz plik $FRIENDLY_NAME]($DOWNLOAD_URL)" >> $GITHUB_STEP_SUMMARY
          echo "Adres: $DOWNLOAD_URL" >> $GITHUB_STEP_SUMMARY
