---
# Copyright (C) 2023 Maxwell G <maxwell@gtmx.me>
# SPDX-License-Identifier: GPL-3.0-or-later

"on":
  # This workflow does not execute untrusted code from pull requests and all
  # inputs are properly sanitized,
  pull_request_target: # zizmor: ignore[dangerous-triggers]
    types:
    - opened  # default
    - synchronize  # default
    - reopened  # default
    - ready_for_review  # used in PRs created from GitHub Actions workflows
    branches:
      - devel
      - "stable-*"
  issues:
    types:
      - opened
  workflow_dispatch:
    inputs:
      type:
        required: true
        type: choice
        options:
          - issue
          - pr
      number:
        required: true
        type: number

name: "Triage Issues and PRs"

permissions:
  contents: read

jobs:
  label_prs:
    runs-on: ubuntu-latest
    environment: github-bot
    name: "Label Issue/PR"
    steps:
      - name: Print event information
        env:
          event_json: "${{ toJSON(github.event) }}"
        run: |
          echo "${event_json}"
      - name: Generate temp GITHUB_TOKEN
        id: create_token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ secrets.BOT_APP_ID }}
          private-key: ${{ secrets.BOT_APP_KEY }}
      - name: Checkout parent repository
        uses: actions/checkout@v6
        with:
          persist-credentials: false
      - name: Install Python 3.12
        uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - name: Set up UV
        run: curl -LsSf https://astral.sh/uv/install.sh | sh
      - name: Setup venv
        run: |
          uv venv venv
          uv pip install --python venv \
            -e hacking/pr_labeler -c tests/pr_labeler.txt
      - name: "Run the issue labeler"
        if: "github.event.issue || inputs.type == 'issue'"
        env:
          event_json: "${{ toJSON(github.event) }}"
          GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
          number: "${{ github.event.issue.number || inputs.number }}"
        run: |
          ./venv/bin/ad-triage issue "${number}"
      - name: "Run the PR labeler"
        if: "github.event.pull_request || inputs.type == 'pr'"
        env:
          event_json: "${{ toJSON(github.event) }}"
          GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
          number: "${{ github.event.number || inputs.number }}"
        run: |
          ./venv/bin/ad-triage pr "${number}"
