name: SITL Integration

# Run manually or on schedule (nightly on main).
# Requires Docker Compose SITL harness (docker-compose.sitl.yml).
on:
  workflow_dispatch:
    inputs:
      sitl_speedup:
        description: SITL simulation speedup factor (default 1)
        default: "1"
        type: string
  schedule:
    # Nightly at 02:00 UTC on main branch
    - cron: "0 2 * * *"

jobs:
  sitl-integration:
    name: SITL GPS_INPUT integration
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - uses: actions/checkout@v4

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

      - name: Build gps-denied image
        run: docker build -t gps-denied-onboard:sitl .

      - name: Pull ArduPilot SITL image
        run: docker pull ardupilot/ardupilot-dev:latest

      - name: Start SITL services
        run: |
          docker compose -f docker-compose.sitl.yml up -d ardupilot-sitl gps-denied
          echo "Waiting for SITL to become healthy..."
          for i in $(seq 1 30); do
            if docker compose -f docker-compose.sitl.yml ps ardupilot-sitl \
               | grep -q "healthy"; then
              echo "SITL is healthy"
              break
            fi
            echo "  attempt $i/30..."
            sleep 5
          done

      - name: Run SITL integration tests
        run: |
          docker compose -f docker-compose.sitl.yml run \
            --rm \
            -e ARDUPILOT_SITL_HOST=ardupilot-sitl \
            -e ARDUPILOT_SITL_PORT=5762 \
            integration-tests

      - name: Collect logs on failure
        if: failure()
        run: |
          docker compose -f docker-compose.sitl.yml logs ardupilot-sitl > sitl.log 2>&1
          docker compose -f docker-compose.sitl.yml logs gps-denied > gps-denied.log 2>&1

      - name: Upload logs
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: sitl-logs
          path: |
            sitl.log
            gps-denied.log
          retention-days: 7

      - name: Stop SITL services
        if: always()
        run: docker compose -f docker-compose.sitl.yml down -v
