# GMD regression tests on CI.
#
# This mirrors the smoke workflow's emulator setup but keeps PR execution
# opt-in through regression-label.yml. Nightly scheduled runs execute the
# Phase 1 full aggregate; label/reusable calls execute the core tier. Manual
# runs default to core but can opt into full via run_full.
name: Regression
permissions:
  contents: read

on:
  workflow_dispatch:
    inputs:
      run_full:
        description: 'Run full regression suite (regressionFullCheck) instead of core only'
        type: boolean
        default: false
  workflow_call:
  schedule:
    - cron: '17 8 * * *'

jobs:
  regression:
    name: GMD Regression Tests
    runs-on: ubuntu-latest
    timeout-minutes: 90
    outputs:
      skip_nightly: ${{ steps.check_commits.outputs.skip }}
    concurrency:
      group: regression-${{ github.ref }}
      cancel-in-progress: true
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          lfs: true

      - name: Check for recent commits
        id: check_commits
        if: github.event_name == 'schedule'
        run: |
          commit_time=$(git log -1 --invert-grep --grep='\[skip ci\]' --format=%ct)
          current_time=$(date +%s)
          diff=$((current_time - commit_time))
          # 24 hours (86400) + 5 min buffer
          if [ "$diff" -gt 86700 ]; then
            echo "No commits in the last 24 hours. Skipping nightly run."
            echo "skip=true" >> $GITHUB_OUTPUT
          else
            echo "New commits detected. Running nightly checks."
            echo "skip=false" >> $GITHUB_OUTPUT
          fi

      - name: Set up JDK 17
        if: github.event_name != 'schedule' || steps.check_commits.outputs.skip != 'true'
        uses: actions/setup-java@v5
        with:
          java-version: '17'
          distribution: 'temurin'

      - name: Set up Gradle
        if: github.event_name != 'schedule' || steps.check_commits.outputs.skip != 'true'
        uses: gradle/actions/setup-gradle@v6
        with:
          cache-read-only: ${{ github.ref != 'refs/heads/master' }}
          cache-cleanup: on-success

      - name: Grant execute permission for gradlew
        if: github.event_name != 'schedule' || steps.check_commits.outputs.skip != 'true'
        run: chmod +x gradlew

      - name: Enable KVM
        if: github.event_name != 'schedule' || steps.check_commits.outputs.skip != 'true'
        run: |
          echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \
            | sudo tee /etc/udev/rules.d/99-kvm4all.rules
          sudo udevadm control --reload-rules
          sudo udevadm trigger --name-match=kvm

      - name: Run Regression Check
        if: github.event_name != 'schedule' && !(github.event_name == 'workflow_dispatch' && inputs.run_full)
        run: ./gradlew regressionCheck -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect

      - name: Run Nightly Regression Checks
        if: (github.event_name == 'schedule' && steps.check_commits.outputs.skip != 'true') || (github.event_name == 'workflow_dispatch' && inputs.run_full)
        run: ./gradlew regressionFullCheck -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect

      - name: Upload Managed Device Reports
        if: always() && (github.event_name != 'schedule' || steps.check_commits.outputs.skip != 'true')
        uses: actions/upload-artifact@v7
        with:
          name: gmd-regression-test-reports
          path: |
            app/build/reports/androidTests/managedDevice/
            app/build/outputs/androidTest-results/managedDevice/
            app/build/outputs/androidTest-results/regression-core-preserved/
            app/build/outputs/managed_device_android_test_additional_output/
            macrobenchmark/build/reports/androidTests/managedDevice/
            macrobenchmark/build/outputs/androidTest-results/managedDevice/
            macrobenchmark/build/outputs/managed_device_android_test_additional_output/
          if-no-files-found: warn
          retention-days: 7

  aggregate-results:
    name: Aggregate & Publish Regression Stats
    runs-on: ubuntu-latest
    needs: regression
    # Only aggregate/publish to the dashboard for nightly scheduled runs OR
    # manual runs that execute the full suite (since core-only runs do not
    # generate regression-core-preserved/, publishing would result in incomplete stats).
    if: >
      always() &&
      (needs.regression.result == 'success' || needs.regression.result == 'failure') &&
      needs.regression.outputs.skip_nightly != 'true' &&
      (
        github.event_name == 'schedule' ||
        (github.event_name == 'workflow_dispatch' && inputs.run_full)
      )
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          ref: ${{ github.ref_name }}
          lfs: true


      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.x'

      - name: Download Managed Device Reports
        uses: actions/download-artifact@v8
        with:
          name: gmd-regression-test-reports
          path: tmp-reports
      - name: Aggregate and Push Results
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          mkdir -p .git/info
          echo "app/coverage-baselines/*.ec -filter -diff -merge" >> .git/info/attributes
          git reset --hard HEAD

          git fetch origin ${{ github.sha }}

          for i in {1..3}; do
            echo "Attempt $i to aggregate and push..."
            git pull --rebase origin ${{ github.ref_name }}
            git checkout ${{ github.sha }} -- tools/

            python3 tools/aggregate_regression.py
            git add docs/regression-history.json docs/regression-dashboard.md
            if git diff --quiet && git diff --staged --quiet; then
              echo "No changes to dashboard."
              if [ -f tmp-reports/infra_failed.txt ]; then
                echo "ERROR: Infrastructure failure detected during aggregation!"
                exit 1
              fi
              exit 0
            fi
            git commit -m "docs: update nightly regression dashboard [skip ci]"
            if git push origin ${{ github.ref_name }}; then
              echo "Successfully pushed dashboard update."
              if [ -f tmp-reports/infra_failed.txt ]; then
                echo "ERROR: Infrastructure failure detected during aggregation!"
                exit 1
              fi
              exit 0
            else
              echo "Push failed (concurrent commit). Retrying..."
              git reset --hard HEAD~1
            fi
          done
          echo "Failed to push dashboard update after 3 attempts."
          exit 1
