name: Auto Label PR

on:
  # Runs only on pull_request_target due to having access to a App token.
  # This means PRs from forks will not be able to alter this workflow to get the tokens
  pull_request_target:
    types: [labeled, opened, reopened, synchronize, edited]

permissions:
  pull-requests: write
  contents: read

env:
  SMALL_PR_THRESHOLD: 30
  MEDIUM_PR_THRESHOLD: 100
  MAX_LABELS: 15
  TOO_BIG_THRESHOLD: 1000
  COMPONENT_LABEL_THRESHOLD: 10

jobs:
  label:
    runs-on: ubuntu-latest
    if: github.event.pull_request.state == 'open' && (github.event.action != 'labeled' || github.event.sender.type != 'Bot')
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Generate a token
        id: generate-token
        uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
        with:
          client-id: ${{ vars.ESPHOME_GITHUB_APP_CLIENT_ID }}
          private-key: ${{ secrets.ESPHOME_GITHUB_APP_PRIVATE_KEY }}

      - name: Auto Label PR
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          github-token: ${{ steps.generate-token.outputs.token }}
          script: |
            const script = require('./.github/scripts/auto-label-pr/index.js');
            await script({ github, context });
