// 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'
        CARGO_TARPAULIN_VERSION = '0.37.5'
        BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
        BADGE_OWNER = 'idle-org'
        BADGE_PROJECT = 'epoch_forge'
        BADGE_DEFAULT_BRANCH = 'main'
    }

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

                sh '''
                    set -eu

                    git submodule sync --recursive
                    git submodule update --init --recursive

                    # Jenkins may reuse workspaces. Never trust badges or
                    # completion markers left by an earlier build.
                    rm -rf -- coverage
                    mkdir -m 0755 coverage
                '''
            }
        }

        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 "Installing/updating repository toolchain..."
                    rustup show

                    # The repository's .rust-toolchain.toml selects the
                    # appropriate Rust version automatically.
                    rustup toolchain install 1.92.0 \
                        --profile minimal \
                        --component rustfmt \
                        --component clippy

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

                    if ! cargo tarpaulin --version 2>/dev/null \
                        | grep -F "$CARGO_TARPAULIN_VERSION" >/dev/null; then
                        echo "Installing cargo-tarpaulin $CARGO_TARPAULIN_VERSION..."
                        cargo install cargo-tarpaulin \
                            --version "$CARGO_TARPAULIN_VERSION" \
                            --locked
                    fi

                    cargo tarpaulin --version
                '''
            }
        }

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

                    echo "Checking Rust formatting..."
                    cargo fmt --all -- --check
                '''
            }
        }

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

                    echo "Checking all workspace targets..."
                    cargo check \
                        --workspace \
                        --all-targets \
                        --all-features \
                        --locked
                '''
            }
        }

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

                    echo "Running workspace tests..."
                    cargo test \
                        --workspace \
                        --all-targets \
                        --all-features \
                        --locked

                    case "$BUILD_NUMBER" in
                        ''|*[!0-9]*)
                            echo "ERROR: BUILD_NUMBER is not numeric: $BUILD_NUMBER" >&2
                            exit 1
                            ;;
                    esac
                    : > "coverage/.tests-passed-$BUILD_NUMBER"
                '''
            }
        }

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

                    echo "Measuring workspace line coverage (minimum 65%)..."
                    cargo tarpaulin \
                        --workspace \
                        --all-features \
                        --locked \
                        --output-dir coverage

                    summary=coverage/tarpaulin-report.json
                    [ -f "$summary" ] && [ -s "$summary" ] || {
                        echo "ERROR: Tarpaulin did not create $summary." >&2
                        exit 1
                    }

                    coverage_value=$(sed -n \
                        's/.*"coverage":\([0-9][0-9.]*\),"covered":[0-9][0-9]*,"coverable":[0-9][0-9]*}$/\1/p' \
                        "$summary")
                    if ! awk -v value="$coverage_value" 'BEGIN {
                        valid = value ~ /^[0-9]+([.][0-9]+)?$/ && value >= 0 && value <= 100
                        exit(valid ? 0 : 1)
                    }'; then
                        echo "ERROR: invalid overall coverage in $summary: $coverage_value" >&2
                        exit 1
                    fi

                    scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
                    rm -f "$summary"
                    : > "coverage/.coverage-ready-$BUILD_NUMBER"
                '''
            }
        }

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

                    echo "Running Clippy..."
                    cargo clippy \
                        --workspace \
                        --all-targets \
                        --all-features \
                        --locked \
                        -- \
                        -D warnings
                '''
            }
        }

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

                    echo "Building release binaries..."
                    cargo build \
                        --workspace \
                        --release \
                        --all-features \
                        --locked

                    echo
                    echo "Release build completed."
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Rust CI',
                summary: 'Epoch Forge passed tests, coverage, and all CI checks.',
                text: 'Formatting, workspace checks, tests, the coverage floor, Clippy, and the release build passed. Badge artifacts are finalized during cleanup.',
                title: 'Build Successful'
            )

            echo '✅ Epoch Forge passed all CI checks.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Rust CI',
                summary: 'Epoch Forge failed CI.',
                text: 'Formatting, compilation, tests, coverage, Clippy, or the release build failed. Cleanup still generates current badge artifacts; check the Jenkins log.',
                title: 'Build Failed'
            )

            echo '❌ Epoch Forge CI failed.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Rust CI',
                summary: 'Epoch Forge CI is unstable.',
                text: 'The Jenkins build is unstable. Cleanup still generates current test, coverage, and version badge artifacts.',
                title: 'Build Unstable'
            )

            echo '⚠️ Epoch Forge CI is unstable.'
        }

        cleanup {
            script {
                sh '''
                    set -eu

                    test_marker="coverage/.tests-passed-$BUILD_NUMBER"
                    coverage_marker="coverage/.coverage-ready-$BUILD_NUMBER"

                    if [ -f "$test_marker" ]; then
                        scripts/ci-coverage-badges.sh test --value passing
                    else
                        scripts/ci-coverage-badges.sh test --value failing
                    fi

                    if [ ! -f "$coverage_marker" ]; then
                        scripts/ci-coverage-badges.sh coverage --value -
                    fi

                    version=$(awk '
                        /^\[package\][[:space:]]*$/ { in_package = 1; next }
                        /^\[/ && in_package { exit }
                        in_package && /^[[:space:]]*version[[:space:]]*=/ {
                            line = $0
                            sub(/^[^=]*=[[:space:]]*"/, "", line)
                            sub(/"[[:space:]]*$/, "", line)
                            print line
                            exit
                        }
                    ' bin_efo/Cargo.toml)
                    [ -n "$version" ] || {
                        echo "ERROR: could not read efo version from bin_efo/Cargo.toml." >&2
                        exit 1
                    }
                    scripts/ci-coverage-badges.sh version --value "$version"

                    rm -f coverage/tarpaulin-report.json \
                        "$test_marker" "$coverage_marker"

                    for badge in version test coverage; do
                        path="coverage/$badge.svg"
                        if [ -L "$path" ] || [ ! -f "$path" ] || [ ! -s "$path" ]; then
                            echo "ERROR: invalid badge artifact: $path" >&2
                            exit 1
                        fi
                    done
                '''

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

                if (env.BRANCH_NAME == env.BADGE_DEFAULT_BRANCH) {
                    sh '''
                        set -eu
                        scripts/publish-ci-coverage-badges.sh \
                            "$BADGE_PUBLICATION_ROOT" \
                            "$BADGE_OWNER" \
                            "$BADGE_PROJECT" \
                            "$BADGE_DEFAULT_BRANCH" \
                            version test coverage
                    '''
                } else {
                    echo "Skipping public badge publication for branch ${env.BRANCH_NAME ?: '(unset)'}; default is ${env.BADGE_DEFAULT_BRANCH}."
                }
            }
        }
    }
}
