name: Tests

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

# Minimum test coverage percentage required to pass CI.
# Current: ~50%. Target: gradually increase to 55 -> 60 -> 70.
env:
  COVERAGE_THRESHOLD: 50

jobs:
  test:
    name: Test
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        go: ['1.26.4']
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Download dependencies
        run: go mod download

      - name: Verify code compiles
        shell: bash
        run: go build ./...

      - name: Run go vet
        shell: bash
        run: go vet ./...

      - name: Run tests
        shell: bash
        run: go test -race -coverprofile=coverage.txt -covermode=atomic `go list ./... | grep -v ./pkg/proto/livedebugger`
        
      - name: Enforce coverage threshold
        if: matrix.os == 'ubuntu-latest'
        shell: bash
        run: |
          COVERAGE=$(go tool cover -func=coverage.txt | grep total | awk '{print $3}' | sed 's/%//')
          echo "Total coverage: ${COVERAGE}%"
          echo "Threshold: ${COVERAGE_THRESHOLD}%"

          if [ -z "$COVERAGE" ]; then
            echo "::error::Could not determine coverage percentage"
            exit 1
          fi

          # Compare as integers (truncate decimals) to avoid bc dependency
          COVERAGE_INT=${COVERAGE%.*}
          if [ "$COVERAGE_INT" -lt "$COVERAGE_THRESHOLD" ]; then
            echo "::error::Coverage ${COVERAGE}% is below the ${COVERAGE_THRESHOLD}% threshold"
            exit 1
          fi

          echo "Coverage ${COVERAGE}% meets the ${COVERAGE_THRESHOLD}% threshold"

      - name: Generate coverage report
        if: matrix.os == 'ubuntu-latest'
        shell: bash
        run: |
          echo "### Coverage Report" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
          go tool cover -func=coverage.txt | tail -20 >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY

      - name: Upload coverage to Codecov
        if: matrix.os == 'ubuntu-latest'
        uses: codecov/codecov-action@v4
        with:
          files: ./coverage.txt
          fail_ci_if_error: false
