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

pipeline {
    agent { label 'rust_no_docker' }

    options { disableConcurrentBuilds() }

    environment {
        CARGO_TERM_COLOR = 'always'

        // CI-only staging directory.
        CI_ARTIFACT_DIR = '.ci-artifacts'
        DEPLOY_DIR = '/mnt/books/Reports'
        DIAGNOSTICS_AUTHOR = 'Beffroi'
    }

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

                sh '''
                    set -eu

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

        stage('Setup Typst') {
            steps {
                sh '''
                    set -eu

                    # ---------------------------------------------------------
                    # cargo-binstall
                    # ---------------------------------------------------------

                    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

                    # ---------------------------------------------------------
                    # Typst
                    # ---------------------------------------------------------

                    if ! command -v typst >/dev/null 2>&1; then
                        echo "Typst not found — installing typst-cli..."

                        cargo binstall \
                            --no-confirm \
                            typst-cli
                    else
                        echo "Typst already installed."
                    fi

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

        stage('Setup Packaging') {
            steps {
                sh '''
                    set -eu
                    uv venv --allow-existing .ci-venv
                    uv pip install --python .ci-venv/bin/python -r tools/packaging-requirements.txt
                '''
            }
        }

        stage('Validate') {
            steps {
                sh '''
                    set -eu
                    bash -n render.sh render-diagnostics.sh tools/package-reports.sh
                    .ci-venv/bin/python -c "import pyzipper"
                    command -v python3
                    typst compile --root . tools/check-diagnostics.typ /tmp/check-diagnostics.pdf
                    for fixture in tools/fixtures/*.json; do
                        typst compile --root . --input diagnostics="$fixture" --input author="CI validation" diagnostics.typ /tmp/check-diagnostics-render.pdf
                    done
                '''
            }
        }

        stage('Render Reports') {
            steps {
                sh '''
                    set -eu
                    # Only clear generated build outputs, never source PDFs.
                    rm -rf "${CI_ARTIFACT_DIR}"
                    ./render.sh --clean --all
                    ./render-diagnostics.sh --clean --all "${DIAGNOSTICS_AUTHOR}"
                '''
            }
        }

        stage('Package Reports') {
            environment {
                REPORT_ZIP_PASSWORD = credentials('typst-reporter-publish-password')
            }
            steps {
                sh '''
                    set +x
                    set -eu
                    PACKAGING_PYTHON=.ci-venv/bin/python ./tools/package-reports.sh build "${CI_ARTIFACT_DIR}"
                '''
                archiveArtifacts artifacts: '.ci-artifacts/*.zip', fingerprint: true
            }
        }

        stage('Publish Reports') {
            steps {
                sh '''
                    set -eu
                    mkdir -p "${DEPLOY_DIR}"
                    # Rename complete uploads on the destination filesystem.
                    for archive in Reports.zip Diagnostics.zip; do
                        cp "${CI_ARTIFACT_DIR}/${archive}" "${DEPLOY_DIR}/.${archive}.tmp"
                        mv -f "${DEPLOY_DIR}/.${archive}.tmp" "${DEPLOY_DIR}/${archive}"
                    done
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Report CI',
                summary: 'typst_reporter passed all CI checks.',
                text: 'Validation, rendering, encrypted ZIP packaging, and publication completed successfully.',
                title: 'Encrypted reports published'
            )

            echo '✅ typst_reporter published encrypted report archives.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Report CI',
                summary: 'typst_reporter failed CI.',
                text: 'A validation, rendering, packaging, or publication step failed. Check the Jenkins log.',
                title: 'Report CI failed'
            )

            echo '❌ typst_reporter CI failed.'
        }

        unstable {
            publishChecks(
                conclusion: 'ACTION_REQUIRED',
                name: 'Report CI',
                summary: 'typst_reporter CI is unstable.',
                text: 'The Jenkins build completed with an unstable status.',
                title: 'Report CI unstable'
            )

            echo '⚠️ typst_reporter CI is unstable.'
        }

        always {
            echo 'CI finished.'
        }
    }
}