# PR validation: smoke tests on pull request
apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: styrened-pr-validation
  namespace: argo
spec:
  arguments:
    parameters:
      - name: commit-sha
      - name: pr-number
      - name: repo
        value: styrene-lab/styrened
  entrypoint: pipeline
  serviceAccountName: ci-workflow-sa

  # Report status back to GitHub on completion
  hooks:
    exit:
      template: report-github-status

  volumeClaimTemplates:
    - metadata:
        name: workspace
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: local-path
        resources:
          requests:
            storage: 5Gi

  volumes:
    - name: ghcr-auth
      secret:
        secretName: ghcr-secret

  templates:
    - name: pipeline
      dag:
        tasks:
          - name: set-pending
            template: github-status
            arguments:
              parameters:
                - name: state
                  value: pending
                - name: description
                  value: "Smoke tests running..."
          - name: checkout
            template: git-checkout
          - name: build-test
            template: nix-build-test
            depends: "checkout"
          - name: smoke-tests
            template: run-smoke-tests
            depends: "build-test"

    - name: git-checkout
      container:
        image: alpine/git:latest
        command: [sh, -c]
        args:
          - |
            set -euo pipefail
            TOKEN=$(cat /ghcr/password)
            git clone --depth 50 \
              https://x-access-token:${TOKEN}@github.com/{{workflow.parameters.repo}}.git \
              /workspace/src
            cd /workspace/src
            git fetch origin pull/{{workflow.parameters.pr-number}}/head
            git checkout {{workflow.parameters.commit-sha}}
        volumeMounts:
          - name: workspace
            mountPath: /workspace
          - name: ghcr-auth
            mountPath: /ghcr
            readOnly: true
        resources:
          requests:
            cpu: 100m
            memory: 128Mi

    - name: nix-build-test
      container:
        image: nixos/nix:latest
        command: ["/bin/sh", "-c"]
        env:
          - name: PATH
            value: "/root/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/bin:/usr/bin"
        args:
          - |
            set -euo pipefail
            mkdir -p /etc/nix
            echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf
            echo "sandbox = false" >> /etc/nix/nix.conf

            cd /workspace/src
            echo "Building test OCI image..."
            nix build .#oci-test --no-link --print-out-paths > /workspace/oci-test-path
            echo "Build complete: $(cat /workspace/oci-test-path)"
        volumeMounts:
          - name: workspace
            mountPath: /workspace
        resources:
          requests:
            cpu: "1"
            memory: 2Gi
          limits:
            cpu: "4"
            memory: 4Gi

    - name: run-smoke-tests
      container:
        image: python:3.11-slim
        command: [sh, -c]
        args:
          - |
            set -eu
            mkdir -p /workspace/results

            # Install curl
            apt-get update -qq && apt-get install -qq -y curl >/dev/null 2>&1

            # Install kubectl
            echo "=== Installing kubectl ==="
            curl -sLO "https://dl.k8s.io/release/$(curl -sL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
            install kubectl /usr/local/bin/kubectl && rm kubectl

            # Install helm
            echo "=== Installing helm ==="
            curl -sL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash >/dev/null 2>&1

            # Install Python test dependencies
            echo "=== Installing Python dependencies ==="
            pip install --quiet pytest pytest-asyncio pytest-xdist kubernetes pyyaml msgpack-python

            # Verify tools
            echo "=== Tool versions ==="
            kubectl version --client --short 2>/dev/null || kubectl version --client
            helm version --short
            python3 --version

            cd /workspace/src

            # Use existing dev tag from GHCR for smoke tests
            export STYRENED_TEST_IMAGE_TAG="dev"
            echo "Using test image: ghcr.io/styrene-lab/styrened-test:${STYRENED_TEST_IMAGE_TAG}"

            echo "=== Running smoke tests ==="
            pytest tests/k8s/scenarios/ -m smoke -v --tb=short \
              --junitxml=/workspace/results/smoke-results.xml \
              2>&1 | tee /workspace/results/smoke-output.log
        volumeMounts:
          - name: workspace
            mountPath: /workspace
        resources:
          requests:
            cpu: 500m
            memory: 512Mi
          limits:
            cpu: "2"
            memory: 1Gi
      activeDeadlineSeconds: 600

    - name: github-status
      inputs:
        parameters:
          - name: state
          - name: description
            default: ""
      container:
        image: curlimages/curl:latest
        command: [sh, -c]
        args:
          - |
            STATE="{{inputs.parameters.state}}"
            DESC="{{inputs.parameters.description}}"
            [ -z "$DESC" ] && DESC="Argo Workflows CI"
            curl -sf -X POST \
              -H "Authorization: token $(cat /ghcr/password)" \
              -H "Accept: application/vnd.github+json" \
              "https://api.github.com/repos/{{workflow.parameters.repo}}/statuses/{{workflow.parameters.commit-sha}}" \
              -d "{\"state\":\"${STATE}\",\"target_url\":\"https://argo.vanderlyn.house/workflows/argo/{{workflow.name}}\",\"description\":\"${DESC}\",\"context\":\"argo/smoke-tests\"}"
        volumeMounts:
          - name: ghcr-auth
            mountPath: /ghcr
            readOnly: true

    - name: report-github-status
      container:
        image: curlimages/curl:latest
        command: [sh, -c]
        args:
          - |
            if [ "{{workflow.status}}" = "Succeeded" ]; then
              STATE="success"
              DESC="Smoke tests passed"
            else
              STATE="failure"
              DESC="Smoke tests failed"
            fi
            curl -sf -X POST \
              -H "Authorization: token $(cat /ghcr/password)" \
              -H "Accept: application/vnd.github+json" \
              "https://api.github.com/repos/{{workflow.parameters.repo}}/statuses/{{workflow.parameters.commit-sha}}" \
              -d "{\"state\":\"${STATE}\",\"target_url\":\"https://argo.vanderlyn.house/workflows/argo/{{workflow.name}}\",\"description\":\"${DESC}\",\"context\":\"argo/smoke-tests\"}"
        volumeMounts:
          - name: ghcr-auth
            mountPath: /ghcr
            readOnly: true
