name: Coverage Compare (Main)

on:
  workflow_call:

jobs:
  compare:
    name: Coverage Diff
    runs-on: ubuntu-latest
    steps:
      - name: Checkout (scripts only)
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
        with:
          sparse-checkout: .github/scripts
          fetch-depth: 1

      - name: Download Current Coverage
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
        with:
          name: coverage-summary.json
          path: current/

      - name: Download Previous Main Coverage
        id: prev
        env:
          GH_TOKEN: ${{ github.token }}
          REPO: ${{ github.repository }}
          BRANCH: ${{ github.ref_name }}
          CURRENT_RUN_ID: ${{ github.run_id }}
        run: |
          OUTPUT=$(./.github/scripts/coverage/download-previous.sh previous)
          echo "$OUTPUT"
          grep -q "has_previous=true" <<<"$OUTPUT" && echo "has_previous=true" >> "$GITHUB_OUTPUT" || echo "has_previous=false" >> "$GITHUB_OUTPUT"

      - name: Compare Coverage
        env:
          HAS_PREVIOUS: ${{ steps.prev.outputs.has_previous }}
        run: |
          PREV_FILE="previous/coverage-summary.json"
          [[ "$HAS_PREVIOUS" != "true" ]] && PREV_FILE="nonexistent"
          ./.github/scripts/coverage/compare-coverage.sh current/coverage-summary.json "$PREV_FILE" comparison-report.json

      - name: Write Summary
        if: always()
        env:
          REPORT_MODE: significant-only
        run: ./.github/scripts/coverage/write-summary.sh comparison-report.json

      - name: Upload comparison-report.json
        if: always()
        uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
        with:
          name: comparison-report.json
          path: comparison-report.json
          retention-days: 30

      - name: Upload comparison-report.html
        if: always()
        uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
        with:
          name: comparison-report.html
          path: comparison-report.html
          retention-days: 30

      - name: Notify Slack
        if: always() && hashFiles('comparison-report.json') != '' && github.ref == 'refs/heads/main' && env.COVERAGE_SLACK_WEBHOOK_URL != ''
        env:
          COVERAGE_SLACK_WEBHOOK_URL: ${{ secrets.COVERAGE_SLACK_WEBHOOK_URL }}
          TAG_NAME: ${{ github.ref_name }}@${{ github.sha }}
          REPO: ${{ github.repository }}
          REPORT_MODE: significant-only
        run: ./.github/scripts/coverage/notify-slack.sh comparison-report.json
