pipeline {
    agent any

    environment {
        GRADLE_USER_HOME = '/var/jenkins_home/.gradle'
        GRADLE_OPTS = '-Dorg.gradle.parallel=true -Dorg.gradle.caching=true'
        JAVA_TOOL_OPTIONS = '-Djava.awt.headless=true'
        JAVA_OPTS = '-Xmx2g'
        TESTS_STARTED = 'false'
        VERIFICATION_SUCCEEDED = 'false'
    }

    stages {
        stage('Clean') {
            steps {
                // A separate successful clean prevents publishing a previous build's reports.
                withGradle {
                    sh './gradlew clean --no-daemon --console=plain'
                }
            }
        }
        stage('Tests and coverage') {
            steps {
                script { env.TESTS_STARTED = 'true' }
                withChecks(name: 'Test', includeStage: true) {
                    withGradle {
                        // --continue finishes independent tests/reports but retains a nonzero exit on failure.
                        sh './gradlew test jacocoTestReport --continue --parallel --max-workers=2 --build-cache --no-daemon --console=plain'
                    }
                }
                script { env.VERIFICATION_SUCCEEDED = 'true' }
            }
        }
    }

    post {
        always {
            script {
                if (env.TESTS_STARTED == 'true') {
                    // Isolate publishers so a failed publisher does not suppress the other diagnostics.
                    catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                        junit testResults: '**/build/test-results/test/TEST-*.xml',
                            checksName: 'Test / Tests and coverage',
                            allowEmptyResults: env.VERIFICATION_SUCCEEDED != 'true'
                        if (env.VERIFICATION_SUCCEEDED == 'true' && !fileExists('prometeu-packer/prometeu-packer-v1/build/test-results/test/TEST-p.packer.services.PackerAssetContractTest.xml')) {
                            error 'Successful verification is missing the packer contract test report.'
                        }
                    }
                    catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                        if (fileExists('build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml')) {
                            withChecks(name: 'JaCoCo Coverage', includeStage: false) {
                                recordCoverage(tools: [[parser: 'JACOCO', pattern: 'build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml']],
                                    id: 'jacoco',
                                    name: 'JaCoCo Coverage',
                                    checksName: 'JaCoCo Coverage',
                                    enabledForFailure: true,
                                    failOnError: true,
                                    sourceDirectories: [[path: 'glob:**/src/main/java']],
                                    sourceCodeEncoding: 'UTF-8',
                                    sourceCodeRetention: 'EVERY_BUILD',
                                    qualityGates: [
                                        [threshold: 50.0, metric: 'CLASS', baseline: 'PROJECT', criticality: 'UNSTABLE'],
                                        [threshold: 50.0, metric: 'METHOD', baseline: 'PROJECT', criticality: 'UNSTABLE'],
                                        [threshold: 50.0, metric: 'LINE', baseline: 'PROJECT', criticality: 'UNSTABLE'],
                                        [threshold: 50.0, metric: 'INSTRUCTION', baseline: 'PROJECT', criticality: 'UNSTABLE'],
                                        [threshold: 40.0, metric: 'BRANCH', baseline: 'PROJECT', criticality: 'UNSTABLE']])
                            }
                        } else if (env.VERIFICATION_SUCCEEDED == 'true') {
                            error 'Successful verification is missing the consolidated JaCoCo XML report.'
                        } else {
                            echo 'Verification failed before consolidated coverage was available; preserving available test reports.'
                        }
                    }
                    catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                        publishHTML(target: [
                            allowMissing: env.VERIFICATION_SUCCEEDED != 'true',
                            alwaysLinkToLastBuild: false,
                            keepAll: true,
                            reportDir: 'build/reports/jacoco/jacocoTestReport/html',
                            reportFiles: 'index.html',
                            reportName: 'Coverage Report'
                        ])
                    }
                    catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                        // Keep raw coverage data even when report generation fails.
                        archiveArtifacts artifacts: '**/build/test-results/test/**, **/build/reports/tests/test/**, **/build/reports/jacoco/**, **/build/jacoco/*.exec',
                            allowEmptyArchive: env.VERIFICATION_SUCCEEDED != 'true',
                            onlyIfSuccessful: false
                    }
                } else {
                    echo 'Preparation did not complete; no current test run to publish. See the build console for diagnostics.'
                }
            }
        }
    }
}
