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

pipeline {
    agent { label 'rust_no_docker' }

    environment {
        SOURCE_FILE = "main.typ"
        OUTPUT_FILE = "Ravenous_build.pdf"
        PUBLISHED_FILE = "Ravenous.pdf"
        BALANCE_SOURCE_FILE = "balance_report.typ"
        BALANCE_OUTPUT_FILE = "Ravenous_balance_report_build.pdf"
        BALANCE_PUBLISHED_FILE = "Ravenous_balance_report.pdf"

        // Important: published books live under /mnt/books
        DEPLOY_DIR = "/mnt/books/Ravenous"
    }

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

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

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

                    if ! command -v cargo-binstall >/dev/null 2>&1; then
                        echo "cargo-binstall not found — installing it..."
                        cargo install cargo-binstall
                    else
                        echo "cargo-binstall already installed."
                    fi

                    if ! command -v typst >/dev/null 2>&1; then
                        echo "Typst not found — installing it..."
                        cargo binstall --no-confirm typst-cli
                    else
                        echo "Typst already installed."
                    fi

                    echo "Using:"
                    typst --version
                '''
            }
        }

        stage('Build PDFs') {
            steps {
                sh '''
                    set -e

                    echo "Generating build metadata"
                    ./tools/pseudo_toolchain.sh

                    echo "Building ${SOURCE_FILE} -> ${OUTPUT_FILE}"
                    typst compile "${SOURCE_FILE}" "${OUTPUT_FILE}"

                    echo "Building ${BALANCE_SOURCE_FILE} -> ${BALANCE_OUTPUT_FILE}"
                    typst compile "${BALANCE_SOURCE_FILE}" "${BALANCE_OUTPUT_FILE}"

                    test -f "${OUTPUT_FILE}"
                    test -f "${BALANCE_OUTPUT_FILE}"

                    echo "Builds complete:"
                    ls -lh "${OUTPUT_FILE}" "${BALANCE_OUTPUT_FILE}"
                '''
            }
        }

        stage('Archive PDFs') {
            steps {
                archiveArtifacts(
                    artifacts: "${OUTPUT_FILE},${BALANCE_OUTPUT_FILE}",
                    fingerprint: true
                )
            }
        }

        stage('Deploy PDFs') {
            steps {
                script {
                    def reviewBranches = [
                        'origin/lighthouse',
                        'lighthouse'
                    ]

                    def devBranches = [
                        'origin/candlelight',
                        'candlelight'
                    ]

                    def masterBranches = [
                        'origin/lighthouse',
                        'lighthouse'
                    ]

                    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 (masterBranches.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: 'Build Successful',
                summary: 'The Ravenous rulebook and balance report were built successfully.',
                text: 'The rulebook and balance report were compiled and published successfully.',
                title: 'Build Successful'
            )

            echo '✅ Ravenous book and balance report built and published!'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Build Failed',
                summary: 'A Ravenous PDF build or deployment failed.',
                text: 'Rulebook or balance-report compilation/publication failed.',
                title: 'Build Failed'
            )

            echo '❌ A Ravenous PDF failed to build or publish.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Build Unstable',
                summary: 'The Ravenous rulebook build is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Build Unstable'
            )

            echo '⚠️ Ravenous build is unstable.'
        }
    }
}


/**
 * Publish the generated Ravenous PDFs.
 *
 * Build artifacts retain explicit CI names in Jenkins, while published copies
 * use stable rulebook and balance-report names.
 *
 * @param targetDir Directory receiving the compiled book.
 */
def deployTo(String targetDir) {
    sh """
        set -e

        echo "Publishing Ravenous and its balance report to ${targetDir}"

        mkdir -p "${targetDir}"

        rsync -a \
            "${env.OUTPUT_FILE}" \
            "${targetDir}/${env.PUBLISHED_FILE}"

        rsync -a \
            "${env.BALANCE_OUTPUT_FILE}" \
            "${targetDir}/${env.BALANCE_PUBLISHED_FILE}"

        echo "Published:"
        ls -lh \
            "${targetDir}/${env.PUBLISHED_FILE}" \
            "${targetDir}/${env.BALANCE_PUBLISHED_FILE}"
    """
}
