name: Runtime Build

on:
  pull_request:
    paths:
      - ".github/workflows/runtime-build.yml"
      - "pyproject.toml"
      - "uv.lock"
      - "runtimes/**"
      - "scripts/discover_runtime_matrix.py"
  push:
    branches:
      - main
    paths:
      - ".github/workflows/runtime-build.yml"
      - "pyproject.toml"
      - "uv.lock"
      - "runtimes/**"
      - "scripts/discover_runtime_matrix.py"
  workflow_dispatch:

jobs:
  discover:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.runtime-matrix.outputs.matrix }}

    steps:
      - uses: actions/checkout@v6

      - uses: astral-sh/setup-uv@v7

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.13.11"

      - name: Sync environment
        run: uv sync

      - name: Discover runtime matrix
        id: runtime-matrix
        run: |
          matrix="$(uv run python scripts/discover_runtime_matrix.py)"
          echo "matrix=${matrix}" >> "$GITHUB_OUTPUT"

  build:
    needs: discover
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix: ${{ fromJSON(needs.discover.outputs.matrix) }}

    steps:
      - uses: actions/checkout@v6

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

      - name: Build ${{ matrix.name }} runtime
        uses: docker/build-push-action@v7
        with:
          context: ${{ matrix.build_context }}
          file: ${{ matrix.dockerfile }}
          platforms: linux/amd64
          tags: ${{ matrix.image }}
          load: true
          push: false
          cache-from: type=gha,scope=runtime-${{ matrix.name }}
          cache-to: type=gha,scope=runtime-${{ matrix.name }},mode=max

      - name: Smoke check ${{ matrix.name }} runtime
        run: docker run --rm "${{ matrix.image }}" python --version
