name: Ruff

on:
  pull_request:
    branches: [ main ]
  push:
    branches: [ main ]

permissions:
  contents: write

jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
      with:
        ref: ${{ github.event.pull_request.head.ref || github.ref }}
        repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
        token: ${{ secrets.GITHUB_TOKEN }}
    - uses: actions/setup-python@v6
      with:
        python-version: '3.11'
    - name: Install uv
      uses: astral-sh/setup-uv@v7
    - name: Install dependencies
      run: uv sync
    - name: Auto-fix ruff lint and format
      if: github.event_name == 'pull_request'
      run: |
        uv run ruff check --fix
        uv run ruff format
    - name: Commit and push fixes
      if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
      run: |
        git diff --quiet && exit 0
        git config user.name "github-actions[bot]"
        git config user.email "github-actions[bot]@users.noreply.github.com"
        git add -A
        git commit -m "style: auto-fix ruff lint and format"
        git push
    - name: Validate
      run: |
        uv run ruff check
        uv run ruff format --check
