name: Python Tests

on:
  push:
    branches: [main, master, develop]
  pull_request:
    branches: [main, master, develop]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.11", "3.12"]

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

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}

      - name: Cache dependencies
        uses: actions/cache@v3
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
          restore-keys: |
            ${{ runner.os }}-pip-

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip

          # Install all requirements files if they exist
          for req in requirements.txt requirements-*.txt; do
            if [ -f "$req" ]; then
              echo "Installing $req..."
              pip install -r "$req"
            fi
          done

      - name: Lint with flake8
        run: |
          pip install flake8
          # Stop the build if there are Python syntax errors or undefined names
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
          # Exit-zero treats all errors as warnings
          flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
        continue-on-error: true

      - name: Test with pytest
        if: ${{ hashFiles('pytest.ini') != '' || hashFiles('tests/') != '' }}
        run: |
          pip install pytest pytest-cov pytest-asyncio
          pytest --cov=. --cov-report=xml --cov-report=term
        continue-on-error: true

      - name: Upload coverage to Codecov
        if: ${{ hashFiles('pytest.ini') != '' || hashFiles('tests/') != '' }}
        uses: codecov/codecov-action@v3
        with:
          file: ./coverage.xml
          fail_ci_if_error: false
