 pipeline {
    agent {
        docker { image 'python:3.12-slim' }
    }

    parameters {
        string(name: 'FAIL_ON', defaultValue: 'critical', description: 'Minimum severity that fails the build')
    }

    stages {
        stage('Install') {
            steps {
                sh 'pip install meridian-mcp'
            }
        }

        stage('Scan') {
            steps {
                // Capture the real exit code rather than letting Jenkins'
                // default `sh` step abort the stage immediately — the SARIF
                // report still needs to be generated and archived even when
                // the scan fails the severity gate.
                script {
                    env.SCAN_EXIT_CODE = sh(
                        script: "meridian scan \"${WORKSPACE}\" --fail-on \"${params.FAIL_ON}\"",
                        returnStatus: true
                    ).toString()
                }
            }
        }

        stage('Report') {
            steps {
                sh "meridian report \"${WORKSPACE}\" --format sarif --output meridian-results.sarif"
                sh "meridian report \"${WORKSPACE}\" --format markdown --output meridian-report.md"
                archiveArtifacts artifacts: 'meridian-results.sarif,meridian-report.md', allowEmptyArchive: false
                // Requires the "Warnings Next Generation" plugin with its
                // SARIF parser — guarded with a try/catch since the exact
                // DSL has shifted across plugin versions and this step
                // should never break the pipeline if that plugin isn't
                // installed. archiveArtifacts above is the guaranteed,
                // plugin-free way to get the SARIF file out of this build.
                script {
                    try {
                        recordIssues(tools: [sarif(pattern: 'meridian-results.sarif')])
                    } catch (err) {
                        echo "Skipping recordIssues (Warnings Next Generation plugin not available or DSL differs): ${err}"
                    }
                }
            }
        }

        stage('Gate') {
            steps {
                script {
                    if (env.SCAN_EXIT_CODE != '0') {
                        error("Meridian scan failed the '${params.FAIL_ON}' severity gate (exit code ${env.SCAN_EXIT_CODE}).")
                    }
                }
            }
        }
    }
}
