/**
 * ----------------------------------------------------------------------------
 *          ____  _____________  __
 *         / __ \/ ____/ ___/\ \/ /                 _   _   _
 *        / / / / __/  \__ \  \  /                 / \ / \ / \
 *       / /_/ / /___ ___/ /  / /               = ( M | S | K )=
 *      /_____/_____//____/  /_/                   \_/ \_/ \_/
 *
 * ----------------------------------------------------------------------------
 * Default pipeline for multibranch Jenkins pipeline project
 * Checks linting, builds, and publishes tagged versions to PyPI
 * ----------------------------------------------------------------------------
 */

pipeline {
    agent any

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

    stages {
        stage('Environment') {
            steps {
                cleanWs(deleteDirs: true, notFailBuild: true)
                checkout scm
                sh '''
                    python3 -m venv .venv
                    .venv/bin/pip install --upgrade pip
                    .venv/bin/pip install hatch
                '''
            }
        }

        stage('Lint & Test') {
            environment {
                PATH = "${workspace}/.venv/bin:${env.PATH}"
            }
            steps {
                sh 'hatch -e lint run all'
            }
        }

        stage('Build') {
            environment {
                PATH = "${workspace}/.venv/bin:${env.PATH}"
            }
            steps {
                sh 'hatch build'
            }
            post {
                success {
                    archiveArtifacts artifacts: 'dist/*', fingerprint: true
                }
            }
        }

        stage('Publish') {
            when {
                buildingTag()
            }
            environment {
                PYPI_TOKEN = credentials('pypi-token-desyrdl')
                PATH = "${workspace}/.venv/bin:${env.PATH}"
                // Essential to prevent headless SecretStorage/D-Bus deadlocks
                PYTHON_KEYRING_BACKEND = 'keyring.backends.null.Keyring'
            }
            steps {
                sh '''
                    hatch -v publish --yes -u __token__ -a "$PYPI_TOKEN"
                '''
            }
        }
    }

    post {
        always {
            sh 'rm -rf .venv dist'
        }
    }
}