pipeline {
  agent {
    kubernetes {
      label 'lesavka-tests'
      defaultContainer 'rust-ci'
      yaml """
apiVersion: v1
kind: Pod
spec:
  nodeSelector:
    kubernetes.io/arch: arm64
    node-role.kubernetes.io/worker: "true"
  containers:
    - name: rust-ci
      image: rust:1.87-bookworm
      command: ["cat"]
      tty: true
      volumeMounts:
        - name: workspace-volume
          mountPath: /home/jenkins/agent
  volumes:
    - name: workspace-volume
      emptyDir: {}
"""
    }
  }

  options {
    disableConcurrentBuilds()
    disableResume()
  }

  parameters {
    booleanParam(name: 'PUSH_IMAGES', defaultValue: false, description: 'Push images to registry (enable for release runs)')
    string(name: 'QUALITY_GATE_PUSHGATEWAY_URL', defaultValue: 'http://platform-quality-gateway.monitoring.svc.cluster.local:9091', description: 'Pushgateway base URL for quality gate metrics')
    string(name: 'REGISTRY_CREDENTIALS_ID', defaultValue: 'registry-bstein-dev', description: 'Jenkins credentials id for registry.bstein.dev')
  }

  environment {
    REGISTRY = 'registry.bstein.dev'
    IMAGE_PREFIX = "${REGISTRY}/lesavka"
    CARGO_TERM_COLOR = 'always'
    DOCKER_BUILDKIT = '1'
  }

  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }

    stage('Bootstrap CI Toolchain') {
      steps {
        container('rust-ci') {
          sh '''
            set -eu
            apt-get update
            DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
              python3 \
              curl \
              clang \
              llvm \
              pkg-config \
              libssl-dev \
              ca-certificates \
              libgstreamer1.0-dev \
              libgstreamer-plugins-base1.0-dev \
              protobuf-compiler \
              libpango1.0-dev \
              libcairo2-dev \
              libgdk-pixbuf-2.0-dev \
              libgtk-4-dev
            rm -rf /var/lib/apt/lists/*
            rustup component add rustfmt llvm-tools-preview clippy
            if ! cargo llvm-cov --version >/dev/null 2>&1; then
              cargo install --locked cargo-llvm-cov
            fi
          '''
        }
      }
    }

    stage('Format') {
      steps {
        container('rust-ci') {
          sh 'cargo fmt --all -- --check'
        }
      }
    }

    stage('Hygiene') {
      steps {
        container('rust-ci') {
          sh 'scripts/ci/hygiene_gate.sh'
        }
      }
    }

    stage('Testing') {
      steps {
        container('rust-ci') {
          sh 'cargo test -p lesavka_testing'
        }
      }
    }

    stage('Quality Gate') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/quality_gate.sh'
        }
      }
    }

    stage('Build Dist') {
      steps {
        container('rust-ci') {
          sh 'scripts/ci/build-dist.sh'
        }
      }
    }

    stage('Docker Login') {
      when {
        expression { return params.PUSH_IMAGES }
      }
      steps {
        withCredentials([
          usernamePassword(
            credentialsId: params.REGISTRY_CREDENTIALS_ID,
            usernameVariable: 'REGISTRY_USER',
            passwordVariable: 'REGISTRY_PASS'
          )
        ]) {
          sh 'echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin'
        }
      }
    }

    stage('Build Images') {
      when {
        expression { return params.PUSH_IMAGES }
      }
      steps {
        sh 'PUSH_IMAGES=${PUSH_IMAGES} scripts/ci/build-images.sh'
      }
    }
  }

  post {
    always {
      script {
        try {
          archiveArtifacts artifacts: 'dist/*.tar.gz', fingerprint: true, allowEmptyArchive: true
        } catch (Throwable err) {
          echo "archive step unavailable: ${err.class.simpleName}"
        }
      }
    }
  }
}
