// Optional Gitea webhook: http://192.168.1.37:8080/gitea-webhook/post
pipeline {
    agent { label 'rust_no_docker' }

    options {
        skipDefaultCheckout(true)
        timeout(time: 10, unit: 'MINUTES')
        disableConcurrentBuilds()
    }

    parameters {
        booleanParam(name: 'RUN_CLONE_TEST', defaultValue: true,
                     description: 'Test URL repair on a temporary Ravenous clone (requires Gitea access).')
    }

    environment {
        GIT_TERMINAL_PROMPT = '0'
        PYTHONUNBUFFERED = '1'
        PIP_DISABLE_PIP_VERSION_CHECK = '1'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
                sh '''
                    rm -rf coverage
                    mkdir -p coverage
                '''
            }
        }
        stage('Check tools') {
            steps {
                sh 'python3 --version && git --version'
            }
        }
        stage('Set up Python tools') {
            steps {
                sh '''
                    python3 -m venv .venv
                    .venv/bin/python -m pip install -r requirements-ci.txt
                    python3 -m venv .venv-app
                    .venv-app/bin/python -m pip install setuptools==80.9.0
                    .venv-app/bin/python -m pip install --no-build-isolation --no-deps .
                '''
            }
        }
        stage('Dependency vulnerability audit') {
            steps {
                sh '.venv/bin/pip-audit --strict .'
            }
        }
        stage('Dependency license policy') {
            steps {
                sh '.venv/bin/pip-licenses --python=.venv-app/bin/python'
            }
        }
        stage('Unit tests and coverage') {
            steps {
                sh '''
                    .venv/bin/coverage erase
                    .venv/bin/coverage run -m unittest discover -s tests -v
                    .venv/bin/coverage report
                    .venv/bin/coverage json -o coverage/coverage-summary.json
                    coverage_value=$(.venv/bin/python -c 'import json; value = json.load(open("coverage/coverage-summary.json", encoding="utf-8"))["totals"]["percent_covered"]; assert isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= 100; print(value)')
                    scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
                    rm -f coverage/coverage-summary.json
                    touch "coverage/.coverage-ready-${BUILD_NUMBER}"
                '''
            }
        }
        stage('Ravenous clone test') {
            when { expression { params.RUN_CLONE_TEST } }
            steps {
                sh 'python3 -m unittest discover -s integration -v'
            }
        }
        stage('Record test success') {
            steps {
                sh 'touch "coverage/.tests-passed-${BUILD_NUMBER}"'
            }
        }
    }

    post {
        success {
            echo 'repo-fix audit, license policy, tests, and coverage passed; badge generation and archival run during cleanup.'
        }
        failure {
            echo 'repo-fix CI failed; cleanup will generate and archive test, coverage, and version badges for this build.'
        }
        cleanup {
            script {
                sh '''
                    if [ -f "coverage/.tests-passed-${BUILD_NUMBER}" ]; then
                        scripts/ci-coverage-badges.sh test --value passing
                    else
                        scripts/ci-coverage-badges.sh test --value failing
                    fi

                    if [ ! -f "coverage/.coverage-ready-${BUILD_NUMBER}" ]; then
                        scripts/ci-coverage-badges.sh coverage --value -
                    fi

                    version=$(python3 -c 'import fix_submodules; print(fix_submodules.__version__)')
                    scripts/ci-coverage-badges.sh version --value "$version"

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

                    for badge in version test coverage; do
                        path="coverage/${badge}.svg"
                        if [ -L "$path" ] || [ ! -f "$path" ] || [ ! -s "$path" ]; then
                            echo "invalid badge artifact: $path" >&2
                            exit 1
                        fi
                    done
                    set -- coverage/*.svg
                    if [ "$#" -ne 3 ]; then
                        echo "expected exactly three SVG badge artifacts, found $#" >&2
                        exit 1
                    fi
                    for path do
                        case "$path" in
                            coverage/version.svg|coverage/test.svg|coverage/coverage.svg) ;;
                            *) echo "unexpected SVG artifact: $path" >&2; exit 1 ;;
                        esac
                    done
                '''

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

                def branchName = env.BRANCH_NAME ?: env.GIT_BRANCH
                if (!branchName?.trim()) {
                    error('Jenkins must supply BRANCH_NAME (multibranch) or GIT_BRANCH (Pipeline from SCM).')
                }
                if (branchName.startsWith('refs/remotes/origin/')) {
                    branchName = branchName.substring('refs/remotes/origin/'.length())
                } else if (branchName.startsWith('origin/')) {
                    branchName = branchName.substring('origin/'.length())
                }
                if (branchName == 'main') {
                    sh '''
                        scripts/publish-coverage-badges.sh \
                            /mnt/assets/coverage Chado repo-fix main \
                            version test coverage
                    '''
                } else {
                    echo "Skipping mutable badge publication for branch ${branchName}; default branch is main."
                }
            }
        }
    }
}
