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

pipeline {
    agent { label 'rust_nodocker' }

    environment {
        PYTHONUNBUFFERED = '1'
    }

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

                sh '''
                    set -eu

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

        stage('Validate Configs') {
            steps {
                sh '''
                    set -eu

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

                    echo "Validating configuration files..."

                    python3 <<'PY'
import sys
from pathlib import Path
import tomllib

failed = False

# ------------------------------------------------------------
# TOML
# ------------------------------------------------------------

toml_files = sorted(Path(".").rglob("*.toml"))

for path in toml_files:
    print(f"[TOML] {path}")

    try:
        with path.open("rb") as f:
            tomllib.load(f)
    except Exception as exc:
        print(f"ERROR: invalid TOML: {path}: {exc}", file=sys.stderr)
        failed = True


# ------------------------------------------------------------
# YAML
# ------------------------------------------------------------

yaml_files = sorted(
    list(Path(".").rglob("*.yaml")) +
    list(Path(".").rglob("*.yml"))
)

if yaml_files:
    try:
        import yaml
    except ImportError:
        print(
            "ERROR: YAML files found but PyYAML is not installed.",
            file=sys.stderr,
        )
        print(
            "Install it on the worker with: python3 -m pip install pyyaml",
            file=sys.stderr,
        )
        failed = True
    else:
        for path in yaml_files:
            print(f"[YAML] {path}")

            try:
                with path.open("r", encoding="utf-8") as f:
                    list(yaml.safe_load_all(f))
            except Exception as exc:
                print(
                    f"ERROR: invalid YAML: {path}: {exc}",
                    file=sys.stderr,
                )
                failed = True


# ------------------------------------------------------------
# Summary
# ------------------------------------------------------------

print()
print(f"TOML files checked: {len(toml_files)}")
print(f"YAML files checked: {len(yaml_files)}")

if failed:
    sys.exit(1)

print("Structured config files are syntactically valid.")
PY
                '''
            }
        }

        stage('Validate Git Config') {
            steps {
                sh '''
                    set -eu

                    if [ -f gitconfig ]; then
                        echo "Checking gitconfig..."

                        git config \
                            --file gitconfig \
                            --list >/dev/null

                        echo "gitconfig is valid."
                    else
                        echo "No gitconfig found — skipping."
                    fi
                '''
            }
        }
    }

    post {
        success {
            publishChecks(
                conclusion: 'SUCCESS',
                name: 'Config CI',
                summary: 'Configuration sanity checks passed.',
                text: 'TOML, YAML where present, and Git configuration passed basic syntax validation.',
                title: 'Configs Valid'
            )

            echo '✅ Config sanity checks passed.'
        }

        failure {
            publishChecks(
                conclusion: 'FAILURE',
                name: 'Config CI',
                summary: 'Configuration sanity checks failed.',
                text: 'At least one TOML, YAML, or Git configuration file failed syntax validation.',
                title: 'Invalid Config'
            )

            echo '❌ Config sanity checks failed.'
        }
    }
}