// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post

pipeline {
    agent { label 'rust_no_docker' }

    environment {
        CARGO_TERM_COLOR = 'always'
        RUST_BACKTRACE = '1'
        MSRV = '1.98.1'
        CARGO_TARPAULIN_VERSION = '0.37.5'
        CARGO_AUDIT_VERSION = '0.22.2'
        CARGO_DENY_VERSION = '0.20.2'
        BADGE_PUBLISH_ROOT = '/mnt/assets/coverage'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm

                sh '''
                    set -eu

                    git submodule sync --recursive
                    git submodule update --init --recursive
                '''
            }
        }

        stage('Setup Rust') {
            steps {
                sh '''
                    set -eu

                    if ! command -v rustup >/dev/null 2>&1; then
                        echo "ERROR: rustup is not installed on this worker." >&2
                        exit 1
                    fi

                    echo "Ensuring the stable Rust toolchain is available..."

                    rustup toolchain install stable \
                        --profile minimal \
                        --component rustfmt \
                        --component clippy

                    rustup toolchain install "${MSRV}" \
                        --profile minimal

                    rustup default stable

                    echo
                    echo "Using:"
                    rustc --version
                    cargo --version
                    rustfmt --version
                    cargo clippy --version

                    INSTALLED_AUDIT="$(cargo audit --version 2>/dev/null || true)"
                    if [ "${INSTALLED_AUDIT}" != "cargo-audit ${CARGO_AUDIT_VERSION}" ]; then
                        cargo install cargo-audit --locked --version "${CARGO_AUDIT_VERSION}"
                    fi

                    INSTALLED_DENY="$(cargo deny --version 2>/dev/null || true)"
                    if [ "${INSTALLED_DENY}" != "cargo-deny ${CARGO_DENY_VERSION}" ]; then
                        cargo install cargo-deny --locked --version "${CARGO_DENY_VERSION}"
                    fi

                    INSTALLED_TARPAULIN="$(cargo tarpaulin --version 2>/dev/null || true)"
                    if [ "${INSTALLED_TARPAULIN}" != "cargo-tarpaulin-tarpaulin ${CARGO_TARPAULIN_VERSION}" ]; then
                        cargo install cargo-tarpaulin --locked --version "${CARGO_TARPAULIN_VERSION}"
                    fi

                '''
            }
        }

        stage('MSRV') {
            steps {
                sh '''
                    set -eu

                    echo "Checking all targets with Rust ${MSRV}..."

                    cargo "+${MSRV}" check \
                        --locked \
                        --all-targets \
                        --all-features
                '''
            }
        }

        stage('Format') {
            steps {
                sh '''
                    set -eu

                    echo "Checking Rust formatting..."

                    cargo fmt --all -- --check
                '''
            }
        }

        stage('Check') {
            steps {
                sh '''
                    set -eu

                    echo "Checking all targets..."

                    cargo check \
                        --locked \
                        --all-targets \
                        --all-features
                '''
            }
        }

        stage('Test') {
            steps {
                sh '''
                    set -eu

                    echo "Running tests..."

                    cargo test \
                        --locked \
                        --all-targets \
                        --all-features
                '''
            }
        }

        stage('Test Minimal Features') {
            steps {
                sh '''
                    set -eu

                    echo "Running tests without default features..."

                    cargo test \
                        --locked \
                        --all-targets \
                        --no-default-features
                '''
            }
        }

        stage('Fixtures and Goldens') {
            steps {
                sh '''
                    set -eu

                    cargo test --locked --test example_fixtures --all-features
                    cargo test --locked --test cli --all-features

                    mkdir -p coverage
                    : > "coverage/.tests-passed-${BUILD_NUMBER}"
                '''
            }
        }

        stage('Coverage') {
            steps {
                sh '''
                    set -eu

                    cargo tarpaulin \
                        --config tarpaulin.toml \
                        --out Json \
                        --output-dir coverage

                    mv coverage/tarpaulin-report.json coverage/summary.json
                    coverage_percent=$(sed -n \
                        's/^.*],"coverage":\\([0-9][0-9.]*\\),"covered":[0-9][0-9]*,"coverable":[0-9][0-9]*}$/\\1/p' \
                        coverage/summary.json)
                    scripts/render-coverage-badge.sh \
                        "${coverage_percent}" \
                        coverage/coverage.svg
                    rm coverage/summary.json
                    : > "coverage/.coverage-ready-${BUILD_NUMBER}"
                '''
            }
        }

        stage('Clippy') {
            steps {
                sh '''
                    set -eu

                    echo "Running Clippy..."

                    cargo clippy \
                        --locked \
                        --all-targets \
                        --all-features \
                        -- \
                        -D warnings
                '''
            }
        }

        stage('Documentation') {
            steps {
                sh '''
                    set -eu

                    cargo doc --locked --no-deps --all-features
                '''
            }
        }

        stage('Supply Chain') {
            steps {
                sh '''
                    set -eu

                    cargo audit --deny warnings
                    cargo deny --locked check
                '''
            }
        }

        stage('Workspace Packages') {
            steps {
                sh '''
                    set -eu

                    echo "Assembling all publishable workspace packages..."

                    scripts/package-workspace.sh --no-verify
                '''
            }
        }

        stage('Build Release') {
            steps {
                sh '''
                    set -eu

                    echo "Building John Slop release binaries..."

                    # Jenkins reuses workspaces. Remove only ignored release
                    # output so rerunning the same commit stays deterministic.
                    rm -rf -- dist

                    # The packaging script reads and validates Cargo.toml itself.
                    scripts/package-release.sh

                    echo
                    echo "Release build completed."

                    ls -lh \
                        target/release/john-slop \
                        target/release/john-slop-fmt \
                        target/release/john-slop-lsp \
                        dist/*.tar.gz \
                        dist/*.sha256
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Rust CI',
                summary: 'JohnSlop passed all CI checks.',
                text: 'The Linux MSRV/stable matrix, formatting, feature tests, fixtures, coverage and badge generation, docs, Clippy, supply-chain policy, and release build completed successfully.',
                title: 'Build Successful'
            )

            echo '✅ JohnSlop passed all CI checks.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Rust CI',
                summary: 'JohnSlop failed CI.',
                text: 'A toolchain, formatting, test, fixture, coverage, badge generation, documentation, Clippy, supply-chain, or release check failed. Check the Jenkins log.',
                title: 'Build Failed'
            )

            echo '❌ JohnSlop CI failed.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Rust CI',
                summary: 'JohnSlop CI is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Build Unstable'
            )

            echo '⚠️ JohnSlop CI is unstable.'
        }

        cleanup {
            sh '''
                set -eu

                mkdir -p coverage
                test_status=failing
                if [ -f "coverage/.tests-passed-${BUILD_NUMBER}" ]; then
                    test_status=passing
                fi
                scripts/render-test-badge.sh \
                    "${test_status}" \
                    coverage/test.svg

                if [ ! -f "coverage/.coverage-ready-${BUILD_NUMBER}" ]; then
                    scripts/render-coverage-badge.sh - coverage/coverage.svg
                fi

                package_version=$(awk '
                    $0 == "[workspace.package]" { in_package = 1; next }
                    substr($0, 1, 1) == "[" { in_package = 0 }
                    in_package && $1 == "version" && $2 == "=" {
                        gsub(/^"|"$/, "", $3)
                        print $3
                        exit
                    }
                ' Cargo.toml)
                if [ -z "${package_version}" ]; then
                    echo "could not determine workspace package version" >&2
                    exit 2
                fi
                scripts/render-version-badge.sh \
                    "${package_version}" \
                    coverage/version.svg

                rm -f \
                    coverage/summary.json \
                    coverage/tarpaulin-report.json \
                    "coverage/.tests-passed-${BUILD_NUMBER}" \
                    "coverage/.coverage-ready-${BUILD_NUMBER}"
            '''

            archiveArtifacts(
                allowEmptyArchive: false,
                artifacts: 'coverage/coverage.svg,coverage/test.svg,coverage/version.svg',
                fingerprint: true
            )

            sh '''
                set -eu

                if [ "${BRANCH_NAME:-}" = "main" ]; then
                    scripts/publish-badges.sh \
                        "${BADGE_PUBLISH_ROOT}" \
                        coverage \
                        test \
                        version
                fi
            '''
        }
    }
}
