// 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'
        CRAFT_BUILD_DIR = 'craft_web/build'
        EFFECTS_BUILD_DIR = 'effects_web/build'
        DEPLOY_ROOT = '/mnt/assets/ravenous_roll20'
        SHEET_DIR = 'ravenous_sheet'
        CRAFT_DIR = 'ravenous_craft'
        EFFECTS_DIR = 'ravenous_effects'
        BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
        BADGE_OWNER = 'Ravenous'
        BADGE_PROJECT = 'ravenous_roll20'
        DEFAULT_BRANCH = 'main'
    }

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

                sh '''
                    set -e
                    git submodule sync --recursive
                    git submodule update --init --recursive
                    rm -rf coverage
                    mkdir -p coverage
                '''
            }
        }

        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('Install Python SQLite') {
            steps {
                sh '''
                    set -e
                    uv sync --frozen

                    if ! uv run python -c 'import sqlite3' >/dev/null 2>&1; then
                        if [ "$(uname -s)" != FreeBSD ] || ! command -v pkg >/dev/null 2>&1; then
                            echo 'The selected Python lacks sqlite3, and no FreeBSD pkg installer is available.' >&2
                            exit 1
                        fi

                        python_flavor=$(uv run python -c 'import sys; print(f"{sys.version_info.major}{sys.version_info.minor}")')
                        sqlite_package="py${python_flavor}-sqlite3"
                        echo "Installing ${sqlite_package} for the Python used by uv..."
                        if [ "$(id -u)" -eq 0 ]; then
                            pkg install -y "${sqlite_package}"
                        elif command -v sudo >/dev/null 2>&1; then
                            sudo -n pkg install -y "${sqlite_package}"
                        elif command -v doas >/dev/null 2>&1; then
                            doas -n pkg install -y "${sqlite_package}"
                        else
                            echo "Install ${sqlite_package} on the Jenkins agent or grant noninteractive pkg access." >&2
                            exit 1
                        fi
                    fi

                    uv run python -c 'import sqlite3; print("SQLite", sqlite3.sqlite_version)'
                '''
            }
        }

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

                    mkdir -p "${BUILD_DIR}"
                    uv sync --frozen
                    ./scripts/build.sh
                    uv run python craft_web/tools/build.py --output "${CRAFT_BUILD_DIR}"
                    uv run python effects_web/tools/build.py --output "${EFFECTS_BUILD_DIR}"
                    uv run python tools/export_monsters.py --id 2 --output "${BUILD_DIR}/example-monster-2.json"
                    uv run python tools/export_monsters.py --id 5 --output "${BUILD_DIR}/example-monster-5.json"
                    uv run python -m unittest discover -s tests -v
                    uv run python -m unittest discover -s craft_web/tests -v
                    uv run python -m unittest discover -s effects_web/tests -v
                    if command -v node >/dev/null 2>&1; then
                        RAVENOUS_CHARACTER_JSON="${BUILD_DIR}/example-character.json" \
                        RAVENOUS_MONSTER_JSON="${BUILD_DIR}/example-monster-2.json" \
                            node tests/test_character_io.mjs
                        RAVENOUS_MONSTER_JSON="${BUILD_DIR}/example-monster-5.json" \
                            node tests/test_character_io.mjs
                        node tests/test_craft_import.mjs
                        node tests/test_effects_import.mjs
                    else
                        echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator tests.'
                    fi
                    ./scripts/build.sh --check
                    uv run python craft_web/tools/build.py --output "${CRAFT_BUILD_DIR}" --check
                    uv run python effects_web/tools/build.py --output "${EFFECTS_BUILD_DIR}" --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"
                    test -f "${BUILD_DIR}/example-character.json"
                    test -f "${BUILD_DIR}/example-craft-forge.json"
                    test -f "${BUILD_DIR}/example-craft-alchemy.json"
                    test -f "${BUILD_DIR}/example-monster-2.json"
                    test -f "${BUILD_DIR}/example-monster-5.json"
                    test -f "${CRAFT_BUILD_DIR}/index.html"
                    test -f "${CRAFT_BUILD_DIR}/styles.css"
                    test -f "${CRAFT_BUILD_DIR}/app.js"
                    test -f "${CRAFT_BUILD_DIR}/catalog.js"
                    test -f "${CRAFT_BUILD_DIR}/build-info.json"
                    test -f "${EFFECTS_BUILD_DIR}/index.html"
                    test -f "${EFFECTS_BUILD_DIR}/styles.css"
                    test -f "${EFFECTS_BUILD_DIR}/app.js"
                    test -f "${EFFECTS_BUILD_DIR}/catalog.js"
                    test -f "${EFFECTS_BUILD_DIR}/build-info.json"
                    test -f "${EFFECTS_BUILD_DIR}/ravenous-effects-v1.schema.json"

                    echo "Roll20 sheet build complete:"
                    ls -lh "${BUILD_DIR}"
                    echo "Craft workshop build complete:"
                    ls -lh "${CRAFT_BUILD_DIR}"
                    echo "Effects library build complete:"
                    ls -lh "${EFFECTS_BUILD_DIR}"
                    : > "coverage/.tests-passed-$BUILD_NUMBER"
                '''
            }
        }

        stage('Python coverage') {
            steps {
                sh '''
                    set -eu

                    ./scripts/run-python-coverage.sh
                    test -s coverage/coverage-summary.json
                    coverage_value=$(uv run python -c 'import json, math, sys; value=json.load(open(sys.argv[1], encoding="utf-8"))["totals"]["percent_covered"]; assert isinstance(value, (int, float)) and math.isfinite(value) and 0 <= value <= 100; print(f"{value:.1f}")' coverage/coverage-summary.json)
                    ./scripts/ci-coverage-badges.sh coverage --value "$coverage_value"
                    rm -f coverage/coverage-summary.json coverage/.coverage
                    : > "coverage/.coverage-ready-$BUILD_NUMBER"
                '''
            }
        }

        stage('Archive sheet') {
            steps {
                archiveArtifacts(
                    artifacts: 'build/**,craft_web/build/**,effects_web/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
                    def craftTargetDir
                    def effectsTargetDir

                    if (reviewBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}_lighthouse"
                        craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}_lighthouse"
                        effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}_lighthouse"
                    } else if (devBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}_candlelight"
                        craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}_candlelight"
                        effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}_candlelight"
                    } else if (productionBranches.contains(env.BRANCH_NAME)) {
                        targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}"
                        craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}"
                        effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}"
                    } else {
                        echo "Branch '${env.BRANCH_NAME}' is not a publication branch — skipping deployment."
                        return
                    }

                    deployTo(targetDir)
                    deployCraftTo(craftTargetDir)
                    deployEffectsTo(effectsTargetDir)
                }
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Roll20 Sheet Build Successful',
                summary: 'The Ravenous Roll20 sheet was generated and validated successfully.',
                text: 'Builds, tests, the Python coverage floor, and badge generation completed successfully.',
                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: 'A build, test, coverage-floor, badge, or deployment step failed; cleanup records current badge state.',
                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 build is unstable; cleanup generates badges that reflect this build.',
                title: 'Roll20 Sheet Build Unstable'
            )
            echo '⚠️ Ravenous Roll20 sheet build is unstable.'
        }

        cleanup {
            sh '''
                set -eu

                mkdir -p coverage
                if [ -f "coverage/.tests-passed-$BUILD_NUMBER" ]; then
                    ./scripts/ci-coverage-badges.sh test --value passing
                else
                    ./scripts/ci-coverage-badges.sh test --value failing
                fi

                if [ ! -f "coverage/.coverage-ready-$BUILD_NUMBER" ]; then
                    ./scripts/ci-coverage-badges.sh coverage --value -
                fi

                version=$(uv run python -c 'import pathlib, tomllib; print(tomllib.loads(pathlib.Path("pyproject.toml").read_text(encoding="utf-8"))["project"]["version"])')
                ./scripts/ci-coverage-badges.sh version --value "$version"

                rm -f coverage/coverage-summary.json coverage/.coverage \
                    "coverage/.tests-passed-$BUILD_NUMBER" \
                    "coverage/.coverage-ready-$BUILD_NUMBER"

                for badge in version test coverage; do
                    file="coverage/$badge.svg"
                    test -f "$file"
                    test ! -L "$file"
                    test -s "$file"
                done
                count=$(find coverage -maxdepth 1 -type f -name '*.svg' | wc -l | tr -d ' ')
                test "$count" = 3
            '''

            archiveArtifacts(
                allowEmptyArchive: false,
                artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
                fingerprint: true
            )

            script {
                if (!env.BRANCH_NAME) {
                    error('BRANCH_NAME is required; badge publication expects a Jenkins multibranch job.')
                }
                if (env.BRANCH_NAME == env.DEFAULT_BRANCH) {
                    sh '''
                        scripts/publish-coverage-badges.sh \
                            "$BADGE_PUBLICATION_ROOT" \
                            "$BADGE_OWNER" \
                            "$BADGE_PROJECT" \
                            "$DEFAULT_BRANCH" \
                            version test coverage
                    '''
                }
            }
        }
    }
}

/** Publish the static reusable-effects library below the project asset root. */
def deployEffectsTo(String targetDir) {
    def allowedDirs = [
        '/mnt/assets/ravenous_roll20/ravenous_effects',
        '/mnt/assets/ravenous_roll20/ravenous_effects_candlelight',
        '/mnt/assets/ravenous_roll20/ravenous_effects_lighthouse'
    ]
    if (!allowedDirs.contains(targetDir)) {
        error("Refusing to publish effects library to unexpected path: ${targetDir}")
    }

    sh """
        set -e
        echo "Publishing Ravenous effects library to ${targetDir}"
        mkdir -p "${targetDir}"
        rsync -a --delete "${env.EFFECTS_BUILD_DIR}/" "${targetDir}/"
    """
}

/** Publish the static craft workshop below the project asset root. */
def deployCraftTo(String targetDir) {
    def allowedDirs = [
        '/mnt/assets/ravenous_roll20/ravenous_craft',
        '/mnt/assets/ravenous_roll20/ravenous_craft_candlelight',
        '/mnt/assets/ravenous_roll20/ravenous_craft_lighthouse'
    ]
    if (!allowedDirs.contains(targetDir)) {
        error("Refusing to publish craft workshop to unexpected path: ${targetDir}")
    }

    sh """
        set -e
        echo "Publishing Ravenous craft workshop to ${targetDir}"
        mkdir -p "${targetDir}"
        rsync -a --delete "${env.CRAFT_BUILD_DIR}/" "${targetDir}/"
    """
}


/** Publish the Roll20 bundle below the project asset root. */
def deployTo(String targetDir) {
    def allowedDirs = [
        '/mnt/assets/ravenous_roll20/ravenous_sheet',
        '/mnt/assets/ravenous_roll20/ravenous_sheet_candlelight',
        '/mnt/assets/ravenous_roll20/ravenous_sheet_lighthouse'
    ]
    if (!allowedDirs.contains(targetDir)) {
        error("Refusing to publish Roll20 sheet to unexpected path: ${targetDir}")
    }

    sh """
        set -e

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