name: API Diff Report

on: [pull_request, workflow_dispatch]

concurrency:
  group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.head_ref || github.ref }}
  cancel-in-progress: true

env:
  STAGE_PROGRESS: progress
  STAGE_END: end
  PR_API_OUTPUT: ci_outputs/pr_branch_api
  BASE_API_OUTPUT: ci_outputs/base_branch_api
  DIFF_REPORT_OUTPUT: ci_outputs/diff_report

jobs:
  diff_report:
    runs-on: macos-latest
    env:
      FIREBASECI_USE_LATEST_GOOGLEAPPMEASUREMENT: 1

    steps:
      - name: Checkout PR branch
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Copy diff report tools
        run: cp -a scripts/api_diff_report/. ~/api_diff_report

      - id: get_changed_files
        name: Get changed file list
        run: |
          echo "file_list=$(git diff --name-only -r HEAD^1 HEAD | tr '\n' ' ')" >> $GITHUB_OUTPUT

      - name: Setup python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install Prerequisites
        run:  ~/api_diff_report/prerequisite.sh

      - name: Clean Diff Report Comment in PR
        run: |
          python ~/api_diff_report/pr_commenter.py \
            --stage ${{ env.STAGE_PROGRESS }} \
            --token ${{github.token}} \
            --pr_number ${{github.event.pull_request.number}} \
            --commit $GITHUB_SHA \
            --run_id ${{github.run_id}}

      - name: Generate API files for PR branch
        run: |
          python ~/api_diff_report/api_info.py \
            --file_list ${{ steps.get_changed_files.outputs.file_list }} \
            --output_dir ${{ env.PR_API_OUTPUT }}

      - name: Checkout Base branch
        run: git checkout HEAD^

      - name: Generate API files for Base branch
        run: |
          python ~/api_diff_report/api_info.py \
            --file_list ${{ steps.get_changed_files.outputs.file_list }} \
            --output_dir ${{ env.BASE_API_OUTPUT }}

      - name: Generate API Diff Report
        run: |
          python ~/api_diff_report/api_diff_report.py \
            --pr_branch ${{ env.PR_API_OUTPUT }} \
            --base_branch ${{ env.BASE_API_OUTPUT }} \
            --output_dir ${{ env.DIFF_REPORT_OUTPUT }}

      - name: Update Diff Report Comment in PR
        run: |
          python ~/api_diff_report/pr_commenter.py \
            --stage ${{ env.STAGE_END }} \
            --report ${{ env.DIFF_REPORT_OUTPUT }} \
            --token ${{github.token}} \
            --pr_number ${{github.event.pull_request.number}} \
            --commit $GITHUB_SHA \
            --run_id ${{github.run_id}}

      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: api_info_and_report
          path: ci_outputs
          retention-days: 1
