// roam-code Analysis Pipeline for Jenkins
//
// Runs roam-code health checks and rules validation.
// Archives SARIF artifacts and integrates with warnings-ng plugin.
//
// Prerequisites:
//   - Python 3.9+ available on the agent
//   - Jenkins warnings-ng plugin (optional, for SARIF ingestion)
//   - Pipeline Utility Steps plugin (optional, for JSON parsing)
//
// Parameters:
//   ROAM_PYTHON_VERSION: Python command to use (default: python3)
//   ROAM_HEALTH_GATE:    Minimum health score to pass (default: 60)
//
// To customize: copy this file to Jenkinsfile in your project root.
// Generated by: roam ci-setup --platform jenkins

pipeline {
    agent any

    parameters {
        string(name: 'ROAM_HEALTH_GATE', defaultValue: '60', description: 'Minimum health score to pass')
        string(name: 'ROAM_PYTHON', defaultValue: 'python3', description: 'Python executable name')
    }

    environment {
        ROAM_RESULTS = "${WORKSPACE}/roam-results"
    }

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    stages {
        stage('Setup') {
            steps {
                sh '''
                    mkdir -p "${ROAM_RESULTS}"

                    # Create virtual environment for isolation
                    ${ROAM_PYTHON} -m venv .roam-venv
                    . .roam-venv/bin/activate

                    pip install --quiet --upgrade pip
                    pip install --quiet roam-code

                    echo "roam-code version: $(roam --version 2>/dev/null || echo unknown)"
                '''
            }
        }

        stage('Index') {
            steps {
                sh '''
                    . .roam-venv/bin/activate
                    roam init
                '''
            }
        }

        stage('Health Check') {
            steps {
                sh '''
                    . .roam-venv/bin/activate

                    roam --json health > "${ROAM_RESULTS}/health.json"
                    roam health
                '''
            }
        }

        stage('Rules Check') {
            steps {
                sh '''
                    . .roam-venv/bin/activate

                    roam --json check-rules > "${ROAM_RESULTS}/rules.json" || true
                    roam check-rules || true
                '''
            }
        }

        stage('SARIF Reports') {
            steps {
                sh '''
                    . .roam-venv/bin/activate

                    roam --sarif health > "${ROAM_RESULTS}/health.sarif" || true
                    roam --sarif check-rules > "${ROAM_RESULTS}/rules.sarif" 2>/dev/null || true
                '''
            }
        }

        stage('Quality Gate') {
            steps {
                sh '''
                    . .roam-venv/bin/activate

                    HEALTH_SCORE=$(${ROAM_PYTHON} -c "
import json
try:
    data = json.load(open('${ROAM_RESULTS}/health.json'))
    print(data.get('summary', {}).get('health_score', 0))
except Exception:
    print(0)
")
                    echo "Health score: ${HEALTH_SCORE}/100"
                    echo "Gate threshold: ${ROAM_HEALTH_GATE}"

                    if [ "${HEALTH_SCORE}" -lt "${ROAM_HEALTH_GATE}" ]; then
                        echo "FAILED: Health score ${HEALTH_SCORE} below gate ${ROAM_HEALTH_GATE}"
                        exit 1
                    fi

                    echo "PASSED: Health score ${HEALTH_SCORE} meets gate ${ROAM_HEALTH_GATE}"
                '''
            }
        }
    }

    post {
        always {
            // Archive JSON and SARIF results
            archiveArtifacts(
                artifacts: 'roam-results/**',
                allowEmptyArchive: true,
                fingerprint: true
            )

            // Ingest SARIF via warnings-ng plugin (if installed)
            // Install "Warnings Next Generation" plugin for this to work.
            // See: https://plugins.jenkins.io/warnings-ng/
            script {
                try {
                    recordIssues(
                        tools: [sarif(
                            id: 'roam-health',
                            name: 'roam-code Health',
                            pattern: 'roam-results/health.sarif'
                        )],
                        qualityGates: [[
                            threshold: 1,
                            type: 'TOTAL',
                            unstable: true
                        ]]
                    )
                } catch (e) {
                    echo "warnings-ng plugin not available: ${e.message}"
                    echo "Install 'Warnings Next Generation' plugin for SARIF integration"
                }
            }

            script {
                try {
                    recordIssues(
                        tools: [sarif(
                            id: 'roam-rules',
                            name: 'roam-code Rules',
                            pattern: 'roam-results/rules.sarif'
                        )],
                        qualityGates: [[
                            threshold: 1,
                            type: 'TOTAL',
                            unstable: true
                        ]]
                    )
                } catch (e) {
                    // Silently skip if plugin not installed
                }
            }

            // Clean up virtual environment
            sh 'rm -rf .roam-venv || true'
        }

        failure {
            echo 'roam-code analysis failed. Check health score and rules violations above.'
        }

        success {
            echo 'roam-code analysis passed all quality gates.'
        }
    }
}
