name: Kubernetes Integration Tests

on:
  workflow_dispatch:
  pull_request:
    paths:
      - "src/integrations/prefect-kubernetes/prefect_kubernetes/worker.py"
      - "src/integrations/prefect-kubernetes/integration_tests/**"
  push:
    branches: [main]
    paths:
      - "src/integrations/prefect-kubernetes/prefect_kubernetes/worker.py"
      - "src/integrations/prefect-kubernetes/integration_tests/**"

jobs:
  integration-tests:
    name: Run Kubernetes Integration Tests
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Set up uv
        uses: astral-sh/setup-uv@v7
        with:
          enable-cache: true
          python-version: "3.12"
          cache-dependency-glob: "src/integrations/prefect-kubernetes/integration_tests/pyproject.toml"

      - name: Set up Kind cluster
        uses: helm/kind-action@v1.13.0
        with:
          cluster_name: prefect-test

      - name: Install kubectl
        uses: azure/setup-kubectl@v4
        with:
          version: "latest"

      - name: Install krew
        run: |
          (
            set -x; cd "$(mktemp -d)" &&
            OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
            ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
            KREW="krew-${OS}_${ARCH}" &&
            curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
            tar zxvf "${KREW}.tar.gz" &&
            ./"${KREW}" install krew
          )
          echo "${HOME}/.krew/bin" >> $GITHUB_PATH

      - name: Install evict-pod
        run: |
          kubectl krew install evict-pod

      - name: Start Prefect server
        env:
          PREFECT_API_URL: http://127.0.0.1:4200/api
          PREFECT_SERVER_LOGGING_LEVEL: DEBUG
        run: |
          uv run prefect server start --analytics-off --host 0.0.0.0 2>&1 > server.log &
          uv run -s ./scripts/wait-for-server.py

      - name: Run integration tests
        run: |
          uv run pytest -s
        working-directory: src/integrations/prefect-kubernetes/integration_tests
        env:
          PREFECT_API_URL: http://127.0.0.1:4200/api

      - name: Delete Kind cluster
        if: always()
        run: |
          kind delete cluster --name prefect-test
