name: Update sites rating and statistics

on:
  push:
    branches: [ main ]

concurrency:
  group: update-sites-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        ref: main
        fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository.

    - name: Install system dependencies
      run: |
        sudo apt-get update && sudo apt-get install -y libcairo2-dev

    - name: Build application
      run: |
        pip3 install .
        python3 ./utils/update_site_data.py --empty-only

    - name: Regenerate db_meta.json
      run: python3 utils/generate_db_meta.py

    - name: Remove ambiguous main tag
      run: git tag -d main || true

    - name: Check for meaningful changes
      id: check
      run: |
        REAL_CHANGES=$(git diff --unified=0 sites.md | grep '^[+-][^+-]' | grep -v 'The list was updated at' | wc -l)
        if [ "$REAL_CHANGES" -gt 0 ]; then
          echo "has_changes=true" >> $GITHUB_OUTPUT
        else
          echo "has_changes=false" >> $GITHUB_OUTPUT
        fi

    - name: Delete existing PR branch
      if: steps.check.outputs.has_changes == 'true'
      run: git push origin --delete auto/update-sites-list || true

    - name: Create Pull Request
      if: steps.check.outputs.has_changes == 'true'
      uses: peter-evans/create-pull-request@v7
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
        commit-message: "Updated site list and statistics"
        title: "Automated Sites List Update"
        body: "Automated changes to sites.md based on new Alexa rankings/statistics."
        branch: "auto/update-sites-list"
        base: main
        delete-branch: true