name: PR actions

on:
  issue_comment:
    types: [created]

permissions:
  contents: read

env:
  COMMENT: ${{ github.event.comment.body }}
  PR_NUM: ${{ github.event.issue.number }}
  USER_EMAIL: 107717825+opentelemetrybot@users.noreply.github.com
  USER_NAME: opentelemetrybot
  MAX_PATCH_SIZE_KB: 1024

jobs:
  generate-patch:
    name: Run fixer and generate patch (untrusted)
    runs-on: ubuntu-latest
    if: |
      github.event.issue.pull_request &&
      startsWith(github.event.comment.body, '/fix:')

    outputs:
      action_name: ${{ steps.extract.outputs.action_name }}
      patch_name: pr-fix-${{ github.run_id }}
      patch_skipped: ${{ steps.check_patch.outputs.skipped }}

    steps:
      - uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
        with:
          egress-policy: audit

      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          fetch-depth: 999

      - name: Extract action name
        id: extract
        run: |
          PR_ACTION=$(echo "$COMMENT" | grep -oP '/fix:\K[:-_0-9a-z]+')
          echo "action_name=$PR_ACTION" >> "$GITHUB_OUTPUT"

      - run: gh pr checkout $PR_NUM -b "pr-action-${RANDOM}"
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Setup Node
        uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
        with:
          node-version-file: .nvmrc

      - name: Install deps & run fixer
        run: |
          npm install --omit=optional
          npm run fix:${{ steps.extract.outputs.action_name }}

      - name: Generate and validate patch
        id: check_patch
        run: |
          git diff > pr-fix.patch

          if [ ! -s pr-fix.patch ]; then
            echo "No changes detected. Skipping patch."
            echo "skipped=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          actual_size_kb=$(du -k pr-fix.patch | cut -f1)
          if (( actual_size_kb > MAX_PATCH_SIZE_KB )); then
            echo "Patch too large: ${actual_size_kb} KB (limit: ${MAX_PATCH_SIZE_KB} KB)"
            exit 1
          fi

          echo "skipped=false" >> "$GITHUB_OUTPUT"

      - name: Upload patch artifact
        if: steps.check_patch.outputs.skipped != 'true'
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
        with:
          name: pr-fix-${{ github.run_id }}
          path: pr-fix.patch
          retention-days: 1

  apply-patch:
    name: Apply and push patch (trusted)
    runs-on: ubuntu-latest
    needs: generate-patch
    if: needs.generate-patch.outputs.patch_skipped != 'true'
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
        with:
          egress-policy: audit

      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          fetch-depth: 999

      - run: gh pr checkout $PR_NUM -b "pr-action-${RANDOM}"
        env:
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}

      - name: Download patch
        uses: actions/download-artifact@v4
        with:
          name: ${{ needs.generate-patch.outputs.patch_name }}

      - name: Apply patch
        run: |
          git apply --check pr-fix.patch && git apply pr-fix.patch || {
            echo "Patch failed to apply"
            exit 1
          }

      - name: Commit and push changes, if any
        run: |
          git config --local user.email "$USER_EMAIL"
          git config --local user.name "$USER_NAME"
          if [[ $(git status --porcelain) ]]; then
            git add -A
            current_branch=$(git rev-parse --abbrev-ref HEAD)
            echo current_branch=$current_branch
            # gh pr checkout sets some git configs that we can use to make sure
            # we push to the right repo & to the right branch
            remote_repo=$(git config --get branch.${current_branch}.remote)
            echo remote_repo=$remote_repo
            remote_branch=$(git config --get branch.${current_branch}.merge)
            echo remote_branch=$remote_branch
            git commit -m "Results from /fix:${PR_ACTION}"
            git push ${remote_repo} HEAD:${remote_branch}
          else
            echo "No changes to commit"
          fi
        env:
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}

      - name: Comment success
        if: ${{ !failure() && !cancelled() }}
        run: |
          gh pr comment $PR_NUM --body "✅ \`fix:${{ needs.generate-patch.outputs.action_name }}\` applied successfully in [this run]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)."
        env:
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}

      - name: Comment failure
        if: ${{ failure() || cancelled() }}
        run: |
          gh pr comment $PR_NUM --body "❌ \`fix:${{ needs.generate-patch.outputs.action_name }}\` failed. See logs: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
        env:
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}

  notify-noop:
    name: Comment no-op patch
    runs-on: ubuntu-latest
    if: needs.generate-patch.outputs.patch_skipped == 'true'
    needs: generate-patch
    steps:
      - name: Comment no-op
        run: |
          gh pr comment $PR_NUM --body "ℹ️ \`fix:${{ needs.generate-patch.outputs.action_name }}\` made no changes – nothing to commit."
        env:
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}
