name: Check Localization Changes

on:
  pull_request:
    paths:
      - 'src/languages/*.json'
      - 'src/localize/string.json'
  workflow_dispatch:
permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  check-localization:
    runs-on: ubuntu-latest
    env:
      hasIssues: false
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 'latest'

      - name: Install dependencies
        run: npm install json5

      - name: Get changed files
        id: changed-files
        uses: tj-actions/changed-files@v34

      - name: Filter changed localization files
        id: filtered-files
        run: |
          filtered_files=$(echo "${{ steps.changed-files.outputs.all_changed_files }}" | tr ' ' '\n' | grep '^src/languages/.*\.json$' || true)
          echo "filtered_files<<EOF" >> $GITHUB_ENV
          echo "$filtered_files" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV

      - name: Run localization check
        id: check-localization
        run: node scripts/check-localization.js $filtered_files

      - name: Check if diff-report.md exists
        id: check-diff-report
        run: |
          if [ -f scripts/diff-report.md ]; then
            echo "hasIssues=true" >> $GITHUB_ENV
          fi

      - name: Add PR comment if there are issues
        if: env.hasIssues == 'true'
        uses: actions/github-script@v5
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const fs = require('fs');
            const diffReport = fs.readFileSync('scripts/diff-report.md', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: diffReport
            });

      - name: Fail if there are issues
        if: env.hasIssues == 'true'
        run: exit 1
