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

pipeline {
    agent { label 'rust_no_docker' }

    options {
        // We handle checkout explicitly below.
        skipDefaultCheckout(true)
    }

    environment {
        PYTHONUNBUFFERED = '1'
    }

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

                sh '''
                    set -eu

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

        stage('Environment') {
            steps {
                sh '''
                    set -eu

                    echo "System:"
                    uname -a

                    echo
                    echo "Architecture:"
                    uname -m

                    echo
                    echo "Git:"
                    git --version

                    echo
                    echo "Python:"
                    python3 --version

                    echo
                    echo "Repository:"
                    git status --short
                '''
            }
        }

        stage('Validate CI Tools') {
            steps {
                sh '''
                    set -eu

                    if ! command -v python3 >/dev/null 2>&1; then
                        echo "ERROR: python3 is required for WinDiagnostics CI." >&2
                        exit 1
                    fi

                    if [ ! -f tools/check_powershell.py ]; then
                        echo "ERROR: tools/check_powershell.py is missing." >&2
                        exit 1
                    fi

                    echo "Python validator found."
                '''
            }
        }

        stage('Validate PowerShell Sources') {
            steps {
                sh '''
                    set -eu

                    echo "Running lightweight PowerShell integrity checks..."
                    echo

                    python3 tools/check_powershell.py
                '''
            }
        }

        stage('Repository Sanity') {
            steps {
                sh '''
                    set -eu

                    echo "Tracked PowerShell files:"
                    echo

                    ps_files="$(git ls-files -- '*.ps1' '*.psm1' '*.psd1')"

                    if [ -z "${ps_files}" ]; then
                        echo "ERROR: no tracked PowerShell files found." >&2
                        exit 1
                    fi

                    echo "${ps_files}"

                    echo
                    echo "Checking main report script..."

                    if [ ! -f WindowsMaintenanceReport.ps1 ]; then
                        echo "ERROR: WindowsMaintenanceReport.ps1 is missing." >&2
                        exit 1
                    fi

                    if [ ! -s WindowsMaintenanceReport.ps1 ]; then
                        echo "ERROR: WindowsMaintenanceReport.ps1 is empty." >&2
                        exit 1
                    fi

                    echo
                    echo "Repository sanity checks passed."
                '''
            }
        }

        stage('Check JSON Report Contract') {
            steps {
                sh '''
                    set -eu

                    script="WindowsMaintenanceReport.ps1"

                    echo "Checking structured report contract..."
                    echo

                    required_markers="
                    ConvertTo-Json
                    schema_version
                    report_type
                    generated_at
                    completed_at
                    sections
                    "

                    failed=0

                    for marker in ${required_markers}; do
                        if grep -Fq "${marker}" "${script}"; then
                            echo "OK: ${marker}"
                        else
                            echo "ERROR: missing report marker: ${marker}" >&2
                            failed=1
                        fi
                    done

                    if [ "${failed}" -ne 0 ]; then
                        echo >&2
                        echo "Structured JSON report contract validation failed." >&2
                        exit 1
                    fi

                    echo
                    echo "Structured JSON report contract looks valid."
                '''
            }
        }

        stage('Check Repository Hygiene') {
            steps {
                sh '''
                    set -eu

                    echo "Checking repository hygiene..."
                    echo

                    failed=0

                    # ---------------------------------------------------------
                    # Merge conflict markers
                    # ---------------------------------------------------------

                    if git grep -n \
                        -e '^<<<<<<< ' \
                        -e '^=======$' \
                        -e '^>>>>>>> ' \
                        -- \
                        '*.ps1' \
                        '*.psm1' \
                        '*.psd1'
                    then
                        echo >&2
                        echo "ERROR: unresolved merge conflict marker found." >&2
                        failed=1
                    else
                        echo "No merge conflict markers found."
                    fi

                    # ---------------------------------------------------------
                    # Accidentally committed generated/debug files
                    # ---------------------------------------------------------

                    suspicious="$(
                        git ls-files |
                        grep -E \
                            '\\.(tmp|bak|old|orig|rej)$' \
                            || true
                    )"

                    if [ -n "${suspicious}" ]; then
                        echo >&2
                        echo "WARNING: suspicious tracked backup/temp files:"
                        echo "${suspicious}"
                    else
                        echo "No obvious backup/temp files tracked."
                    fi

                    if [ "${failed}" -ne 0 ]; then
                        exit 1
                    fi

                    echo
                    echo "Repository hygiene checks passed."
                '''
            }
        }

        stage('Summary') {
            steps {
                sh '''
                    set -eu

                    echo
                    echo "========================================"
                    echo " WinDiagnostics CI validation complete"
                    echo "========================================"
                    echo
                    echo "Checks performed:"
                    echo "  - Git checkout"
                    echo "  - Python availability"
                    echo "  - PowerShell structural integrity"
                    echo "  - Main script presence"
                    echo "  - JSON report contract"
                    echo "  - Merge conflict detection"
                    echo "  - Repository hygiene"
                    echo
                    echo "NOTE:"
                    echo "  PowerShell/CoreCLR cannot currently run"
                    echo "  on this Jenkins FreeBSD worker."
                    echo
                    echo "  CI therefore performs static structural"
                    echo "  checks instead of invoking pwsh or"
                    echo "  PSScriptAnalyzer."
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'WinDiagnostics CI',
                summary: 'WinDiagnostics passed all CI integrity checks.',
                text: 'Static PowerShell structural validation, repository checks, and JSON report contract validation completed successfully. PowerShell execution is intentionally disabled on this worker.',
                title: 'WinDiagnostics validation successful'
            )

            echo '✅ WinDiagnostics integrity checks passed.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'WinDiagnostics CI',
                summary: 'WinDiagnostics failed CI.',
                text: 'A checkout, repository, PowerShell structural, or JSON report contract validation step failed. Check the Jenkins log.',
                title: 'WinDiagnostics CI failed'
            )

            echo '❌ WinDiagnostics integrity checks failed.'
        }

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

            echo '⚠️ WinDiagnostics CI is unstable.'
        }

        always {
            echo 'CI finished.'
        }
    }
}