name: Mutation Testing

on:
  workflow_dispatch:

concurrency:
  group: mutation-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      should_run: ${{ steps.count.outputs.should_run }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - name: Count lines changed in last 30 days
        id: count
        run: |
          SINCE=$(date -d '30 days ago' +%Y-%m-%d 2>/dev/null || date -v-30d +%Y-%m-%d)
          LINES=$(git log --since="$SINCE" --numstat --pretty="" | awk '{s+=$1+$2} END {print s+0}')
          echo "Lines changed since $SINCE: $LINES"
          if [ "$LINES" -gt 100 ]; then
            echo "should_run=true" >> "$GITHUB_OUTPUT"
          else
            echo "should_run=false" >> "$GITHUB_OUTPUT"
          fi

  mutation-test:
    needs: check-changes
    if: needs.check-changes.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    timeout-minutes: 120

    steps:
      - name: Checkout
        uses: actions/checkout@v7

      - name: Set up JDK 17
        uses: actions/setup-java@v5
        with:
          distribution: sapmachine
          java-version: '17'
          cache: maven

      - name: Set up benchmark repositories
        run: bash scripts/setup-bench-repos.sh

      - name: Build and install test-order plugin
        run: mvn -B -ntp -DskipTests install

      - name: Build cloud-sdk-java (skip tests)
        run: mvn -B -ntp -DskipTests -DskipFormatting install
        working-directory: third-party/cloud-sdk-java

      - name: Run learn pass for connectivity-destination-service
        run: |
          mvn -B -ntp test \
            -pl cloudplatform/connectivity-destination-service \
            -Dtestorder.mode=learn
        working-directory: third-party/cloud-sdk-java

      - name: Run mutation analysis
        run: |
          mvn -B -ntp test-order:analyze-mutations \
            -pl cloudplatform/connectivity-destination-service
        working-directory: third-party/cloud-sdk-java

      - name: Upload mutation report
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: mutation-report-${{ github.run_number }}
          path: third-party/cloud-sdk-java/**/target/test-mutation-results.json
          retention-days: 30

      - name: Print kill rate summary
        if: always()
        run: |
          REPORT=$(find third-party/cloud-sdk-java -name "test-mutation-results.json" | head -1)
          if [ -f "$REPORT" ]; then
            echo "=== Mutation Kill Rate Summary ==="
            python3 -c "
          import json, sys
          with open('$REPORT') as f:
              data = json.load(f)
          print(f\"Overall: {data['totalKilled']}/{data['totalMutants']} ({data['overallKillRate']*100:.1f}%)\")
          print()
          for tc in data.get('testClasses', []):
              print(f\"  {tc['killRate']*100:5.1f}%  {tc['testClass'].split('.')[-1]}  (killed {tc['mutationsKilledByTest']})\")
          "
          else
            echo "No mutation report found"
          fi

  mutation-self:
    needs: check-changes
    if: needs.check-changes.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    timeout-minutes: 90

    steps:
      - name: Checkout
        uses: actions/checkout@v7

      - name: Set up JDK 17
        uses: actions/setup-java@v5
        with:
          distribution: sapmachine
          java-version: '17'
          cache: maven

      - name: Build and install test-order plugin
        run: mvn -B -ntp -DskipTests install

      - name: Run learn pass on test-order-core
        run: |
          mvn -B -ntp test \
            -pl test-order-core \
            -Dtestorder.mode=learn \
            -Dspotless.check.skip=true

      - name: Run mutation analysis on test-order-core
        run: |
          mvn -B -ntp test-order:analyze-mutations \
            -pl test-order-core \
            -Dspotless.check.skip=true

      - name: Upload mutation report (test-order-core)
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: mutation-self-report-core-${{ github.run_number }}
          path: test-order-core/target/test-mutation-results.json
          retention-days: 30

      - name: Print kill rate summary (test-order-core)
        if: always()
        run: |
          REPORT="test-order-core/target/test-mutation-results.json"
          if [ -f "$REPORT" ]; then
            echo "=== test-order-core Mutation Kill Rate ==="
            python3 -c "
          import json, sys
          with open('$REPORT') as f:
              data = json.load(f)
          print(f\"Overall: {data['totalKilled']}/{data['totalMutants']} ({data['overallKillRate']*100:.1f}%)\")
          print()
          for tc in data.get('testClasses', []):
              print(f\"  {tc['killRate']*100:5.1f}%  {tc['testClass'].split('.')[-1]}  (killed {tc['mutationsKilledByTest']})\")
          "
          else
            echo "No mutation report found for test-order-core"
          fi
