name: Review translation PRs

on:
  pull_request_target:
    types: [opened, reopened, synchronize, ready_for_review]
    branches:
      - develop
    paths:
      - "**/*.po"

concurrency:
  group: po-review-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  review-po-pr:
    if: ${{ github.event.pull_request.user.login == 'frappe-pr-bot' }}
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: read
      issues: write
      pull-requests: write

    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.base.sha }}
          fetch-depth: 1
          persist-credentials: false

      - name: Setup Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.14"

      - name: Install helper dependencies
        run: python -m pip install babel

      - name: Build PO review comment
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
        run: python .github/helper/po_pr_review.py --output po-pr-review-comment.md

      - name: Create or update PR comment
        uses: actions/github-script@v8
        with:
          script: |
            const fs = require("fs");
            const marker = "<!-- po-translation-review -->";
            const body = fs.readFileSync("po-pr-review-comment.md", "utf8");
            const { owner, repo } = context.repo;
            const issue_number = context.issue.number;
            const comments = await github.paginate(github.rest.issues.listComments, {
              owner,
              repo,
              issue_number,
              per_page: 100
            });

            const existingComment = comments.find((comment) => comment.body.includes(marker));

            if (existingComment) {
              await github.rest.issues.updateComment({
                owner,
                repo,
                comment_id: existingComment.id,
                body
              });
            } else {
              await github.rest.issues.createComment({
                owner,
                repo,
                issue_number,
                body
              });
            }
