name: Tests

on:
  push:
    branches:
      - main
  pull_request:

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

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4
      with:
        submodules: recursive

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: Cache Docker layers
      uses: actions/cache@v4
      with:
        path: /tmp/.buildx-cache
        key: ${{ runner.os }}-buildx-${{ hashFiles('requirements.txt', 'docker/test/Dockerfile') }}
        restore-keys: |
          ${{ runner.os }}-buildx-

    - name: Build Docker image with cache
      run: |
        cd docker/test
        docker buildx build \
          --cache-from type=local,src=/tmp/.buildx-cache \
          --cache-to type=local,dest=/tmp/.buildx-cache-new,mode=max \
          --load \
          -t kompass:test \
          -f Dockerfile \
          ../../

    - name: Move cache
      run: |
        rm -rf /tmp/.buildx-cache
        mv /tmp/.buildx-cache-new /tmp/.buildx-cache

    - name: Run tests
      run: make test-only

    - name: Check coverage
      run: |
        COVERAGE=$(python3 -c "import json; data=json.load(open('docker/test/htmlcov/coverage.json')); print(data['totals']['percent_covered'])")
        echo "Coverage: ${COVERAGE}%"
        if (( $(echo "$COVERAGE < 100" | bc -l) )); then
          echo "Error: Coverage is ${COVERAGE}%, must be 100%"
          exit 1
        fi
