name: Django Translation Update

on:
  push:
    branches: [ main ]
  # Add manual trigger
  workflow_dispatch:
    inputs:
      reason:
        description: 'Reason for running'
        required: false
        default: 'Manual update of translation files'

# Ensure only one translation job runs at a time
concurrency:
  group: django-translations
  cancel-in-progress: false

jobs:
  update-translations:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    # Skip on PRs from forks (which don't have write permissions)
    # Allow manual runs and pushes to main
    if: github.event_name == 'workflow_dispatch' || github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository)

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.PAT }}
          ref: ${{ github.head_ref }}

      - name: Set up Python 3.11
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: Install gettext
        run: sudo apt-get install -y gettext

      - name: Run makemessages
        run: |
          cd app
          python manage.py makemessages -a

      - name: Check for changes
        id: check_changes
        run: |
          if git diff --exit-code --quiet app/locale/; then
            echo "No translation changes detected"
          else
            echo "changes_detected=true" >> $GITHUB_OUTPUT
            echo "Translation changes detected"
          fi

      - name: Commit translation files
        if: steps.check_changes.outputs.changes_detected == 'true'
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          push_options: --force
          commit_message: |
            chore(locale): update translation files
            
            [skip ci] Automatically generated by Django makemessages workflow
          file_pattern: "app/locale/**/*.po"
