// Gitea multibranch job: idle-org/cockatrice-custom-tokens, default branch main.
// Configure the Gitea webhook at <JENKINS_URL>/gitea-webhook/post.
pipeline {
    agent { label 'rust_nodocker' }

    options {
        skipDefaultCheckout(true)
        disableConcurrentBuilds()
        skipStagesAfterUnstable()
        timestamps()
    }

    environment {
        ASSETS_WEB_ROOT = '/mnt/assets'
        PYTHONDONTWRITEBYTECODE = '1'
        ASSETS_PUBLISHED = 'false'
    }

    stages {
        stage('Checkout') {
            steps {
                deleteDir()
                checkout scm
            }
        }
        stage('Verify worker tools') {
            steps {
                sh '''
                    set -eu
                    for tool in python3 bash git; do
                        if ! command -v "$tool" >/dev/null 2>&1; then
                            echo "Required worker tool is missing: $tool" >&2
                            exit 1
                        fi
                    done
                    python3 --version
                    bash --version
                    git --version
                    python3 -c 'import sys; print("Worker platform:", sys.platform); assert sys.version_info >= (3, 11), "Python 3.11+ is required to build TOML sources"'
                '''
            }
        }
        stage('Install rendering dependency') {
            steps {
                sh '''
                    set -eu
                    python3 -m venv .venv
                    .venv/bin/python -m pip install --require-hashes -r requirements-build.lock
                    .venv/bin/python -c 'import PIL; print("Pillow", PIL.__version__)'
                '''
            }
        }
        stage('Check scripts') {
            steps {
                sh '''
                    set -eu
                    bash -n deploy.sh
                    bash deploy.sh
                '''
            }
        }
        stage('Test generation, installer and publication') {
            steps {
                sh '''
                    set -eu
                    .venv/bin/python -m unittest discover -s tests -v
                '''
            }
        }
        stage('Generate XML and build artifacts') {
            steps {
                sh '''
                    set -eu
                    .venv/bin/python scripts/build.py
                    .venv/bin/python scripts/generate_xml.py --check
                    .venv/bin/python scripts/publish.py prepare
                    .venv/bin/python scripts/publish.py verify
                    sh -n dist/publish/install.sh
                    sh dist/publish/install.sh --help
                '''
            }
        }
        stage('Archive artifacts') {
            steps {
                archiveArtifacts(
                    artifacts: 'dist/*.zip,dist/publish/cards/*,dist/publish/xml/*.xml,dist/publish/install.sh,dist/publish/install.ps1,dist/publish/manifest.json',
                    allowEmptyArchive: false,
                    fingerprint: true
                )
            }
        }
        stage('Publish assets') {
            when {
                allOf {
                    branch 'main'
                    not { changeRequest() }
                }
            }
            steps {
                sh '''
                    set -eu
                    .venv/bin/python scripts/publish.py verify
                    .venv/bin/python scripts/publish.py publish --web-root "$ASSETS_WEB_ROOT"
                '''
                script { env.ASSETS_PUBLISHED = 'true' }
            }
        }
        stage('Publication skipped') {
            when {
                expression { env.BRANCH_NAME != 'main' || env.CHANGE_ID }
            }
            steps {
                echo 'Publication skipped: only main branch builds publish stable assets; change requests never publish.'
            }
        }
    }

    post {
        success {
            script {
                def summary = env.ASSETS_PUBLISHED == 'true'
                    ? 'Checks passed; ZIPs archived and artwork/XML published to assets.dandaedre.com/mtg/.'
                    : 'Checks passed and artifacts archived. Stable publication was skipped for this branch.'
                reportCheck('SUCCESS', 'Build successful', summary)
            }
        }
        failure {
            script {
                reportCheck('FAILURE', 'Build failed', 'A checkout, check, build, archive, or publication step failed. See the Jenkins log; publication may be incomplete.')
            }
        }
        unstable {
            script {
                reportCheck('ACTION_REQUIRED', 'Build unstable', 'The build is unstable. See the Jenkins log; successful publication is not guaranteed.')
            }
        }
    }
}

// Notification failures must not hide or replace the original build result.
def reportCheck(String conclusion, String title, String summary) {
    echo summary
    try {
        publishChecks(
            name: 'Cockatrice assets CI',
            conclusion: conclusion,
            title: title,
            summary: summary,
            text: summary
        )
    } catch (Exception ignored) {
        echo 'Could not report the Gitea check; inspect the Jenkins Checks integration. Original build result retained.'
    }
}
