name: Pull locales from POEditor

on:
  workflow_dispatch:
  schedule:
    - cron: "0 */12 * * *"

permissions:
  contents: write

jobs:
  pull-locales:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 24

      - name: Install dependencies
        run: npm ci

      - name: Debug Variables
        run: |
          echo "Languages to pull: ${{ vars.POEDITOR_LANGUAGES }}"

      - name: Pull locales from POEditor
        run: node .github/scripts/pull-poeditor.mjs
        env:
          POEDITOR_API_TOKEN: ${{ secrets.POEDITOR_API_TOKEN }}
          POEDITOR_PROJECT_ID: ${{ secrets.POEDITOR_PROJECT_ID }}
          POEDITOR_LANGUAGES: ${{ vars.POEDITOR_LANGUAGES }}
          POEDITOR_EXPORT_TYPE: key_value_json

      - name: Verify locales
        run: npm run verify-locales

      - name: Commit changes
        id: commit
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

          # Only stage the locale files we care about
          git add src/locales/*.json

          # Check if there are actually changes STAGED for commit
          if ! git diff --staged --quiet; then
            git commit -m "chore: pull locales from POEditor"
            echo "changes=true" >> "$GITHUB_OUTPUT"
          else
            echo "No locale changes to commit."
            echo "changes=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Push changes
        if: steps.commit.outputs.changes == 'true'
        run: git push

      - name: Purge jsDelivr cache
        if: steps.commit.outputs.changes == 'true'
        run: |
          for file in src/locales/*.json; do
            filename=$(basename "$file")
            url="https://purge.jsdelivr.net/gh/${GITHUB_REPOSITORY}@${GITHUB_REF_NAME}/src/locales/${filename}"
            echo "Purging $url"
            curl -fsS "$url" || echo "Failed to purge $url"
          done
