name: Prefect AWS Docker Test Build

on:
  pull_request:
    paths:
      - "src/integrations/prefect-aws/Dockerfile"
      - ".github/workflows/prefect-aws-docker-images.yaml"
      - ".github/workflows/prefect-aws-docker-test.yaml"

jobs:
  get-versions:
    name: Get Prefect and prefect-aws versions
    runs-on: ubuntu-latest
    outputs:
      PREFECT_VERSION: ${{ steps.get_prefect_version.outputs.PREFECT_VERSION }}
      PREFECT_AWS_VERSION: ${{ steps.get_prefect_aws_version.outputs.PREFECT_AWS_VERSION }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Get latest Prefect version
        id: get_prefect_version
        run: |
          PREFECT_VERSION=$(gh api repos/${{ github.repository }}/releases/latest --jq '.tag_name')
          echo "PREFECT_VERSION=$PREFECT_VERSION" >> $GITHUB_OUTPUT
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Get latest prefect-aws version from tags
        id: get_prefect_aws_version
        run: |
          PREFECT_AWS_VERSION=$(git tag --list 'prefect-aws-*' --sort=-version:refname | head -1 | sed 's/^prefect-aws-//')
          if [ -z "$PREFECT_AWS_VERSION" ]; then
            echo "Unable to determine most recent prefect-aws version!"
            exit 1
          fi
          echo "PREFECT_AWS_VERSION=$PREFECT_AWS_VERSION" >> $GITHUB_OUTPUT

  test-build:
    name: Test build prefect-aws Docker image
    runs-on: ubuntu-latest
    needs: get-versions

    steps:
      - name: Checkout
        uses: actions/checkout@v6

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

      - name: Test Docker build
        uses: docker/build-push-action@v6
        with:
          context: src/integrations/prefect-aws
          platforms: linux/amd64
          build-args: |
            PYTHON_VERSION=3.12
            PREFECT_VERSION=${{ needs.get-versions.outputs.PREFECT_VERSION }}
            PREFECT_AWS_VERSION=${{ needs.get-versions.outputs.PREFECT_AWS_VERSION }}
          push: false
          pull: true
          tags: prefect-aws-test:latest
          load: true

      - name: Test prefect-aws version in image
        run: |
          # Run the image and get the installed prefect-aws version
          INSTALLED_VERSION=$(docker run --rm prefect-aws-test:latest python -c "import prefect_aws; print(prefect_aws.__version__)")
          echo "Expected prefect-aws version: ${{ needs.get-versions.outputs.PREFECT_AWS_VERSION }}"
          echo "Installed prefect-aws version: $INSTALLED_VERSION"

          # Compare versions
          if [ "$INSTALLED_VERSION" != "${{ needs.get-versions.outputs.PREFECT_AWS_VERSION }}" ]; then
            echo "ERROR: Version mismatch!"
            echo "Expected: ${{ needs.get-versions.outputs.PREFECT_AWS_VERSION }}"
            echo "Found: $INSTALLED_VERSION"
            exit 1
          fi

          echo "✅ prefect-aws version matches expected version"
