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

pipeline {
    agent { label 'rust_no_docker' }

    environment {
        UV_CACHE_DIR = "${WORKSPACE}/.uv-cache"
        BUILD_DIR = 'build'
        DEPLOY_DIR = '/mnt/books/ravenous_sheet'
    }

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

                sh '''
                    set -e
                    git submodule sync --recursive
                    git submodule update --init --recursive
                '''
            }
        }

        stage('Install uv') {
            steps {
                sh '''
                    set -e

                    if ! command -v uv >/dev/null 2>&1; then
                        echo "uv not found — installing it with the Rust toolchain..."
                        cargo install --locked uv
                    else
                        echo "uv is already installed."
                    fi

                    uv --version
                '''
            }
        }

        stage('Build and test sheet') {
            steps {
                sh '''
                    set -e

                    mkdir -p "${BUILD_DIR}"
                    uv sync --frozen
                    uv run python tools/build.py
                    uv run python -m unittest discover -s tests -v
                    uv run python tools/build.py --check

                    test -f "${BUILD_DIR}/ravenous.html"
                    test -f "${BUILD_DIR}/ravenous.css"
                    test -f "${BUILD_DIR}/translation.json"
                    test -f "${BUILD_DIR}/sheet.json"
                    test -f "${BUILD_DIR}/build-info.json"

                    echo "Roll20 sheet build complete:"
                    ls -lh "${BUILD_DIR}"
                '''
            }
        }

        stage('Archive sheet') {
            steps {
                archiveArtifacts(
                    artifacts: 'build/**',
                    fingerprint: true
                )
            }
        }

        stage('Deploy sheet') {
            steps {
                script {
                    def reviewBranches = ['origin/lighthouse', 'lighthouse']
                    def devBranches = ['origin/candlelight', 'candlelight']
                    def productionBranches = ['origin/main', 'main', 'origin/master', 'master']
                    def targetDir

                    if (reviewBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_DIR}_lighthouse"
                    } else if (devBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_DIR}_candlelight"
                    } else if (productionBranches.contains(env.BRANCH_NAME)) {
                        targetDir = DEPLOY_DIR
                    } else {
                        echo "Branch '${env.BRANCH_NAME}' is not a publication branch — skipping deployment."
                        return
                    }

                    deployTo(targetDir)
                }
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Roll20 Sheet Build Successful',
                summary: 'The Ravenous Roll20 sheet was generated and validated successfully.',
                text: 'HTML, CSS, translations, manifest, and build metadata are available as Jenkins artifacts.',
                title: 'Roll20 Sheet Build Successful'
            )
            echo '✅ Ravenous Roll20 sheet built successfully!'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Roll20 Sheet Build Failed',
                summary: 'The Ravenous Roll20 sheet build or deployment failed.',
                text: 'Review the Jenkins build, test, deterministic-check, and deployment logs.',
                title: 'Roll20 Sheet Build Failed'
            )
            echo '❌ Ravenous Roll20 sheet failed to build or publish.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Roll20 Sheet Build Unstable',
                summary: 'The Ravenous Roll20 sheet build is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Roll20 Sheet Build Unstable'
            )
            echo '⚠️ Ravenous Roll20 sheet build is unstable.'
        }
    }
}


/** Publish the generated sheet under the books web root. */
def deployTo(String targetDir) {
    sh """
        set -e

        echo "Publishing Ravenous Roll20 sheet to ${targetDir}"
        mkdir -p "${targetDir}"
        rsync -a --delete "${env.BUILD_DIR}/" "${targetDir}/"
    """
}
