// Jenkins Pipeline for PMAT TDG Quality Enforcement
// Auto-generated by `pmat hooks install --tdg-enforcement --ci jenkins`
// DO NOT EDIT MANUALLY - Regenerate with `pmat hooks refresh`
//
// This pipeline enforces quality gates on pull requests and commits:
// - Runs TDG analysis on all code changes
// - Checks for quality regressions against baseline
// - Enforces minimum quality grades for new/modified files
// - Blocks merges that violate configured thresholds
// - Auto-updates baseline on main branch commits
//
// Configuration: .pmat/tdg-rules.toml

pipeline {
    agent any

    environment {
        PMAT_VERSION = '{{PMAT_VERSION}}'
        BASELINE_PATH = '{{BASELINE_PATH}}'
        MIN_GRADE = '{{MIN_GRADE}}'
        MAX_SCORE_DROP = '{{MAX_SCORE_DROP}}'
        MODE = '{{MODE}}'
        CARGO_HOME = "${WORKSPACE}/.cargo"
        PATH = "${CARGO_HOME}/bin:${PATH}"
    }

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

    triggers {
        // Poll SCM for changes every 5 minutes
        pollSCM('H/5 * * * *')
    }

    stages {
        stage('Setup') {
            steps {
                script {
                    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                    echo "📦 PMAT TDG Quality Enforcement Pipeline"
                    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                    echo "Build: ${env.BUILD_NUMBER}"
                    echo "Branch: ${env.BRANCH_NAME}"
                    echo "Baseline: ${env.BASELINE_PATH}"
                    echo "Mode: ${env.MODE}"
                    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                }

                // Checkout with full history for git context
                checkout scm: [
                    $class: 'GitSCM',
                    branches: [[name: '*/main']],
                    extensions: [[$class: 'CloneOption', depth: 0, noTags: false, shallow: false]]
                ]
            }
        }

        stage('Install PMAT') {
            steps {
                script {
                    echo "📦 Installing PMAT v${env.PMAT_VERSION}..."

                    // Check if PMAT is already installed
                    def pmatInstalled = sh(
                        script: 'command -v pmat',
                        returnStatus: true
                    ) == 0

                    if (!pmatInstalled) {
                        sh '''
                            curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
                            . "$HOME/.cargo/env"
                            cargo install pmat --version ${PMAT_VERSION} --force
                        '''
                    }

                    sh 'pmat --version'
                }
            }
        }

        stage('Baseline Check') {
            steps {
                script {
                    echo "🔍 Checking for existing baseline..."

                    def baselineExists = fileExists(env.BASELINE_PATH)

                    if (baselineExists) {
                        echo "✅ Found existing baseline: ${env.BASELINE_PATH}"
                    } else {
                        echo "⚠️  No baseline found, creating initial baseline..."
                        sh """
                            mkdir -p \$(dirname "${env.BASELINE_PATH}")
                            pmat tdg baseline create --output "${env.BASELINE_PATH}" --path .
                        """
                        echo "✅ Initial baseline created"
                    }
                }
            }
        }

        stage('Quality Analysis') {
            parallel {
                stage('Regression Check') {
                    when {
                        changeRequest()
                    }
                    steps {
                        script {
                            echo "🔍 Checking for quality regressions..."

                            def regressionResult = sh(
                                script: """
                                    pmat tdg check-regression \
                                        --baseline "${env.BASELINE_PATH}" \
                                        --path . \
                                        --format table \
                                        --max-score-drop ${env.MAX_SCORE_DROP} \
                                        --fail-on-regression
                                """,
                                returnStatus: true
                            )

                            if (regressionResult != 0) {
                                if (env.MODE == 'warning') {
                                    echo "⚠️  Quality regression detected (warning mode)"
                                    unstable('Quality regression detected')
                                } else {
                                    error "❌ Quality regression detected - blocking merge"
                                }
                            } else {
                                echo "✅ No quality regressions detected"
                            }
                        }
                    }
                }

                stage('Quality Check') {
                    when {
                        changeRequest()
                    }
                    steps {
                        script {
                            echo "📋 Checking quality of new/modified files..."

                            def qualityResult = sh(
                                script: """
                                    pmat tdg check-quality \
                                        --path . \
                                        --format table \
                                        --new-files-only \
                                        --baseline "${env.BASELINE_PATH}" \
                                        --min-grade ${env.MIN_GRADE} \
                                        --fail-on-violation
                                """,
                                returnStatus: true
                            )

                            if (qualityResult != 0) {
                                if (env.MODE == 'warning') {
                                    echo "⚠️  Quality violations detected (warning mode)"
                                    unstable('Quality violations detected')
                                } else {
                                    error "❌ Quality violations detected - blocking merge"
                                }
                            } else {
                                echo "✅ All files meet quality standards"
                            }
                        }
                    }
                }
            }
        }

        stage('Generate Report') {
            steps {
                script {
                    echo "📊 Generating comprehensive TDG report..."

                    sh '''
                        pmat tdg --path . --format json --output tdg-report.json
                        pmat tdg --path . --format markdown --output tdg-report.md
                    '''

                    // Archive reports
                    archiveArtifacts artifacts: 'tdg-report.json,tdg-report.md', allowEmptyArchive: false

                    // Display summary
                    sh 'cat tdg-report.md'
                }
            }
        }

        stage('Update Baseline') {
            when {
                anyOf {
                    branch 'main'
                    branch 'master'
                }
            }
            steps {
                script {
                    echo "📊 Updating baseline for main branch..."

                    sh "pmat tdg baseline update --output '${env.BASELINE_PATH}' --path ."

                    // Commit and push if changed
                    def baselineChanged = sh(
                        script: "git diff --quiet '${env.BASELINE_PATH}'",
                        returnStatus: true
                    ) != 0

                    if (baselineChanged) {
                        withCredentials([usernamePassword(
                            credentialsId: 'jenkins-git-credentials',
                            usernameVariable: 'GIT_USERNAME',
                            passwordVariable: 'GIT_PASSWORD'
                        )]) {
                            sh """
                                git config user.name "jenkins"
                                git config user.email "jenkins@${env.JENKINS_URL}"
                                git add "${env.BASELINE_PATH}"
                                git commit -m "chore: Update TDG baseline [skip ci]

                                Auto-updated by PMAT TDG enforcement pipeline

                                🤖 Generated with PMAT"
                                git push https://${GIT_USERNAME}:${GIT_PASSWORD}@${env.GIT_URL}
                            """
                        }
                        echo "✅ Baseline updated and committed"
                    } else {
                        echo "ℹ️  Baseline unchanged"
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                echo "📊 PMAT TDG Quality Enforcement Summary"
                echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
                echo "Build: ${env.BUILD_NUMBER}"
                echo "Result: ${currentBuild.result}"
                echo "Duration: ${currentBuild.durationString}"
                echo "Branch: ${env.BRANCH_NAME}"
                echo "Baseline: ${env.BASELINE_PATH}"
                echo "Min Grade: ${env.MIN_GRADE}"
                echo "Max Score Drop: ${env.MAX_SCORE_DROP}"
                echo "Mode: ${env.MODE}"
                echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
            }
        }
        success {
            echo "✅ Quality gates passed successfully"
        }
        unstable {
            echo "⚠️  Quality warnings detected (warning mode)"
        }
        failure {
            echo "❌ Quality gates failed"
            echo "Review TDG report and fix quality issues"
        }
    }
}
