pipeline {
  agent {
    docker {
      image 'lifemaps/ci-cpp:latest'
      reuseNode true
      args '-u root:root'
    }
  }

  options {
    timestamps()
    disableConcurrentBuilds()
  }

  environment {
    BUILD_DIR = "build"
    CHANGE_TARGET = "${env.CHANGE_TARGET ?: 'origin/main'}"
  }

  stages {
    stage('Checkout') {
      steps {
        checkout scm
        sh 'git fetch --all --prune'
        sh 'git submodule update --init --recursive || true'
      }
    }

    stage('Policy Checks') {
      steps {
        sh 'python3 ci/check_pr_policies.py'
      }
    }

    stage('Configure') {
      steps {
        sh 'cmake -S . -B ${BUILD_DIR} -G Ninja -DCMAKE_BUILD_TYPE=Debug'
      }
    }

    stage('Build') {
      steps {
        sh 'cmake --build ${BUILD_DIR} --parallel'
      }
    }

    stage('Test') {
      steps {
        sh 'ctest --test-dir ${BUILD_DIR} --output-on-failure'
      }
    }
  }

  post {
    always {
      script {
        if (getContext(hudson.FilePath)) {
          cleanWs deleteDirs: true, disableDeferredWipeout: true
        }
      }
    }
  }
}