name: Gradle Setup
description: Setup Java and Gradle for KMP builds
inputs:
  cache_read_only:
    description: 'Whether Gradle cache is read-only'
    default: 'true'
  jdk_distribution:
    description: 'JDK distribution (temurin or jetbrains)'
    default: 'temurin'
  install_jetbrains_jdk:
    description: 'Also install JetBrains JDK 21 for Compose Desktop toolchain resolution'
    default: 'false'
  gradle_encryption_key:
    description: 'Encryption key for Gradle remote cache'
    required: false
runs:
  using: composite
  steps:
    - name: Copy CI Gradle properties
      shell: bash
      run: mkdir -p ~/.gradle && cp .github/ci-gradle.properties ~/.gradle/gradle.properties

    - name: Validate Gradle Wrapper
      uses: gradle/actions/wrapper-validation@v6

    - name: Set up JDK 21
      uses: actions/setup-java@v5
      with:
        java-version: '21'
        distribution: ${{ inputs.jdk_distribution }}
        token: ${{ github.token }}

    - name: Restore cached JetBrains JDK 21
      if: inputs.install_jetbrains_jdk == 'true'
      id: cache-jbr
      uses: actions/cache@v6
      with:
        path: ${{ runner.tool_cache }}/Java_JetBrains_jdk
        key: jbr-21-${{ runner.os }}-${{ runner.arch }}

    - name: Set up JetBrains JDK 21 (for Compose Desktop)
      if: inputs.install_jetbrains_jdk == 'true' && steps.cache-jbr.outputs.cache-hit != 'true'
      id: setup-jbr
      continue-on-error: true
      uses: actions/setup-java@v5
      with:
        java-version: '21'
        distribution: 'jetbrains'
        check-latest: false
        token: ${{ github.token }}

    - name: JBR setup skipped or failed — Gradle will auto-provision via Foojay
      if: inputs.install_jetbrains_jdk == 'true' && steps.cache-jbr.outputs.cache-hit != 'true' && steps.setup-jbr.outcome == 'failure'
      shell: bash
      run: echo "::warning::JBR setup-java failed (likely GitHub API rate limit). Gradle will auto-provision JBR via Foojay toolchain resolver."

    - name: Setup Gradle
      uses: gradle/actions/setup-gradle@v6
      with:
        cache-read-only: ${{ inputs.cache_read_only }}
        cache-encryption-key: ${{ inputs.gradle_encryption_key }}
        cache-cleanup: on-success
        add-job-summary: always
        gradle-home-cache-includes: |
          caches
          notifications
          ~/.m2/repository/org/robolectric