pipeline {
    agent any

    environment {
        COVERITY_URL = 'http://sumo:8085'
        COVERITY_STREAM = 'agone-full'
        // Add Coverity binaries to PATH if not globally set on the Jenkins agent
        PATH = "/opt/coverity/analysis/bin:${env.PATH}"
    }

    options {
        timestamps()
        timeout(time: 2, unit: 'HOURS')
    }

    stages {
        // =================================================================
        // STAGE 1: AGONE-FULL (Triggers on main/master branch commits or nightlies)
        // =================================================================
        stage('Agone Full Build & Analysis') {
            when {
                // Adjust this condition based on your default branch name
                branch 'main' 
            }
            steps {
                script {
                    echo "Starting agone-full build..."
                    
                    // 1. Clean previous Coverity intermediate directory
                    sh 'rm -rf cov-int'

                    // 2. Run full Bazel build wrapped in cov-build
                    // --spawn_strategy=standalone ensures Coverity intercepts compiler processes
                    sh '''
                        cov-build --dir cov-int \
                            bazel build --spawn_strategy=standalone //:run
                    '''

                    // 3. Analyze captured code
                    sh 'cov-analyze --dir cov-int'

                    // 4. Commit results to Coverity Connect
                    withCredentials([usernamePassword(
                        credentialsId: 'coverity-credentials', 
                        passwordVariable: 'COV_PASSWORD', 
                        usernameVariable: 'COV_USER'
                    )]) {
                        sh """
                            cov-commit-defects --dir cov-int \
                                --url ${COVERITY_URL} \
                                --stream ${COVERITY_STREAM} \
                                --user ${COV_USER} \
                                --password ${COV_PASSWORD}
                        """
                    }
                }
            }
        }

        // =================================================================
        // STAGE 2: AGONE-PR (Triggers on Pull Request branches)
        // =================================================================
        stage('Agone PR Build & Analysis') {
            when {
                // Matches Multibranch Pipeline PR branch patterns (e.g., PR-123)
                changeRequest() 
                // Triggers if running on any branch that is not 'main'
                //not { branch 'main' }
            }
            steps {
                script {
                    echo "Starting agone-pr build..."
                    
                    // 1. Determine target branch and fetch changes
                    def targetBranch = env.CHANGE_TARGET ?: 'main'
                    sh "git fetch origin ${targetBranch}"

                    // 2. Identify changed files relative to the target branch
                    def changedFiles = sh(
                        script: "git diff --name-only origin/${targetBranch}...HEAD",
                        returnStdout: true
                    ).trim()

                    if (!changedFiles) {
                        echo "No files modified in this PR. Skipping build."
                        return
                    }

                    // Write changed files to a temporary file for Coverity / Bazel querying
                    writeFile file: 'changed_files.txt', text: changedFiles

                    // 3. Query Bazel reverse dependencies to find affected targets
                    // Formats file paths into a space-separated list for set() query
                    def bazelQueryTargetSet = changedFiles.split('\n').join(' ')
                    def affectedTargets = sh(
                        script: "bazel query --keep_going \"rdeps(//..., set(${bazelQueryTargetSet}))\" 2>/dev/null || true",
                        returnStdout: true
                    ).trim()

                    if (!affectedTargets) {
                        echo "No Bazel targets affected by modified files. Skipping build."
                        return
                    }

                    echo "Affected Bazel targets:\n${affectedTargets}"

                    // 4. Clean PR-specific Coverity directory
                    sh 'rm -rf cov-int-pr'

                    // 5. Build only the affected targets wrapped in cov-build
                    sh """
                        cov-build --dir cov-int-pr \
                            bazel build --spawn_strategy=standalone ${affectedTargets.replaceAll('\n', ' ')}
                    """

                    // 6. Run fast desktop analysis on only changed files
                    sh """
                        cov-run-desktop --dir cov-int-pr \
                            --target-url ${COVERITY_URL} \
                            --stream ${COVERITY_STREAM} \
                            ${changedFiles.replaceAll('\n', ' ')}
                    """
                }
            }
        }
    }

    post {
        always {
            // Clean up workspace or temporary Bazel artifacts if required
            echo "Pipeline complete."
        }
        failure {
            echo "Pipeline failed. Check build logs for Bazel or Coverity errors."
        }
    }
}
